Search code examples
c++linkerheader-files

How does extern "C" affect linking?


Similar to this question, I am able to compile this program without having to include hello.h in hello.cpp.
But if I use extern "C", then I get an undefined reference to hello in main.cpp during linking. Why is that?

hello.hpp:

extern "C" void hello();

hello.cpp:

//#include "hello.h"
#include <stdio.h>

void hello() { 
    std::cout << "Hello!" << std::endl;
}

main.cpp:

#include "hello.h"

int main() {
    hello();
    return 0;
}

g++ -c main.cpp hello.cpp
g++ main.o hello.o
main.cpp: undefined reference to 'hello'

Solution

  • extern "C" removes the name decoration that most compilers apply to C++ function names. If you're trying to call an undecorated name but you've only compiled a decorated one, they're not going to find each other.