Search code examples
c++cmakeheader-filesclion

Linker errors thrown when defining a function inside of a namespace?


Why am I unable to define a function inside a namespace in a .cpp file (not main.cpp)?

For example, say I want to split my code up into 2 different files, main.cpp, and then lib.cpp (with an associated lib.h file).

The following setup throws a linker error: lib.h:

#ifndef LIB_H_
#define LIB_H_
namespace a{
void foo();
}
#endif

lib.cpp:

#include "lib.h"
using namespace a;
void foo(){
std::cout<<"Hello World!"<<std::endl;
}

main.cpp:

#include "lib.h"
int main(){
a::foo();
return 0;
}

Almost any other variation I can think of works however.

  • Defining the function in the lib.h file instead of lib.cpp works
  • Removing the namespace works
  • Keeping the namespace and instead having foo as a public method in a class which I instantiate in the main function, and then call, works

It seems to me like this might be a convention thing? To encourage people to either use classes or to define the function fully in a .h file? The linker error I'm getting is "undefined symbols(a::foo()) for architecture..."

Why does this happen? I'm on a mac using CLion.


Solution

  • using namespace a; is not a way to define a function inside a namespace.

    The syntax is the same as with the declaration: namespace a { ... }

    #include "lib.h"
    namespace a {
        void foo(){
            std::cout<<"Hello World!"<<std::endl;
        }
    }
    

    For more details refer to: Namespaces.