Search code examples
c++fileheader-filesusing

Linking 2 cpp files that share a .h file


This seems like an straightforward question, but I looked all over and could not find a solution.

So I have 2 .cpp files: a main file, and a function library that the main file needs to see. For various reasons, I do not wish to make a header file for the function library. I do, however, have a header file containing several constant variables that both .cpp files need to see.

It was to my apparently incorrect understanding that the way I would link these 3 files together is by having both cpp files "include" the header file. When I do this, however, main does not have access to the functions in the library. If I add an additional "including library" line to main, I get "error LNK2005". If I try something like having main "include" the library, and have the library "include" the header I also get "error LNK2005".

So... how can I make this set-up work?


Solution

  • The LNK2005 error means that a symbol is defined multiple times.

    This can be related to your "header file containing several constant variables" which breask the one definition rule.

    If you have for example in your header a definition like:

    int MYCONST = 20;     // variable
    

    It will be defined in both compiled cpp files. When linking these together, your linker will notice that there are two definiitions for the same object.

    You have to solve this by declaring the variable in the header (without defining it):

    extern int MYCONST;   // declaration only.  Definition somewhere else
    

    and define it only in one of the file (for example in your function library).

    Or better, defining in the header as a real constant:

    const int MYCONST =20;   // constant (does not offend odr rule)
    

    The one definition rule applies also to function definition (including member functions that would be defined in a class definition in the header).