0

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'
Quaxton Hale
  • 2,460
  • 5
  • 40
  • 71
  • I hesitate to say this is an exact [duplicate](https://stackoverflow.com/q/1041866/22081063) as it doesn't seem to directly answer your specific question, but it might have some useful information for you. – Chipster Jul 01 '23 at 02:29

1 Answers1

2

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    With conventional linkers every function (that isn't local to an object file/library) needs to have a unique name. In C all functions have a unique name (no overloading, no class membership, etc), so name decoration isn't necessary (and the compiler can use either no decoration or a fixed decoration scheme, e.g. prepending a `_`). C++ has function overloading (two functions with the same name and distinct argument types) and decoration is needed so the linker sees each overload as having a unique name. `extern "C"` also can change the mechanism of passing arguments, and returning values. – Peter Jul 01 '23 at 03:19
  • So, in my case, if I included the header file in hello.cpp, the linkage specification would apply to the function declaration (I forgot that I don't have to use extern "C" on the function definition as well). Thus, the undecorated name called in main and defined in hello.cpp are the same and linking is successful. – Quaxton Hale Jul 01 '23 at 03:25