Search code examples
c++definitioninclude-guards

Multiple definitions when using #ifdef


I am having a problem when compiling: Multiple definitions of "myFunction()" I will greatly simplify the problem here. Basically, I have 3 files: "main", "header", and "myLibrary".

  • main.cpp
    #include "header.hpp"

    int main() {  }
  • header.hpp
    #ifndef HEADER_HPP
    #define HEADER_HPP

    #include "myLibrary.hpp"

    // ...

    #endif
  • header.cpp
    #include "header.hpp"

    // ...
  • myLibrary.hpp
    #ifndef LIB_HPP
    #define LIB_HPP

    #if defined(__unix__)
    #include <dlfcn.h>
    std::string myFunction() { return std::string(); }
    #endif

    #endif
  • myLibrary.cpp
    #include "myLibrary.hpp"

    //...

So, why does the compiler say that I have Multiple definitions of "myFunction()"?

One clue I found: When I take header.cpp and erase the line that says #include "header.hpp", the program compiles without complaining. On the other hand, if I erase myFunction (from myLibrary.hpp) instead, the program also compiles without complains


Solution

  • You are defining the body of the function inside the header file. So every translation unit that you include that header in (in this case, main.cpp and header.cpp) will end up with its own copy of that function body. And when you try to link those multiple units together, you get the "duplicate definition" error.

    The function needs to be declared in the hpp file, and defined in the cpp file:

    myLibrary.hpp

    #ifndef LIB_HPP
    #define LIB_HPP
    
    #if defined(__unix__)
    #include <dlfcn.h>
    #include <string>
    std::string myFunction();
    #endif
    
    #endif
    

    myLibrary.cpp

    #include "myLibrary.hpp"
    
    #if defined(__unix__)
    std::string myFunction()
    {
        return std::string();
    }
    #endif
    
    //...