HowTo: Share functions & consts between modules

Hi, i am trying to write functions / consts that are shared across serval modules. But I’m having trouble to compile.

For example, in <MyModule1.cpp>:

#include "plugin.hpp"
#include "test.hpp"

in <MyModule2.cpp>::

#include "plugin.hpp"
#include "test.hpp"

in <test.hpp>

#pragma once
int test(){
    return 2;
}

But when I complied, I got error:

multiple definition of `test()';

What is the correct way to do this? Thanks!

Declare the function in test.hpp

int test();

but don’t implement it there.

Then implement it just once, in a cpp file. You could put it into one of the modules, or into a new shared.cpp or something

#include "test.hpp"
int test() {
  return 2;
}
1 Like

Each of your modules needs to know what the function looks like (input parameters and output type) but they don’t need to know how it works. So the declaration is sufficient. Once the object files are linked to form the dll; that’s when the linker will expect to find just one implementation that it can use to satisfy all the calls.

1 Like

It works! Thanks for saving me hours of head scratching. :grinning:

You could also put the word inline in front of the function definition.

1 Like

Pragma once means only include that file once per compilation unit. So it gets defined in both files. test needs to be defined only once in one compilation unit. Usually this is handled by having only the external declaration of the function in the header & the definition in (for example) test.cpp.

1 Like