Search code examples
c++linker-errorsinlineextern

Already defined in .obj even when using extern and #ifdef


I have three files like this:

head.h

#ifndef HEAD_
#define HEAD_

extern int f();

#endif

mycpp.cpp

#include "head.h"

int f() {
    return 5;
}

myMain.cpp

#include <iostream>
#include "head.h"
#include "mycpp.cpp"

int main()
{
    std::cout << f() << std::endl;
    system("Pause");
    return 0;
}

Running this code produces a link error:

LNK2005 "int __cdecl f(void)" (?f@@YAHXZ) already defined in mycpp.obj

If I add inline to the function f in mycpp.cpp the error goes away.

My question is how to get rid of this error without using the inline function?

P.S. This is an assignment and I can only modify the mycpp.cpp file. So the #include "mycpp.cpp" has to be there.

I know it is a bad idea to include cpp files, but I cannot change the myMain file. It is given this way. And I am not supposed to use inline.


Solution

  • The general rule is: never #include a .cpp file. Only header files should be included.

    Besides that, extern in a function declaration is redundant here. On a variable declaration, extern marks the statement as a declaration rather than a definition. But on function declarations this isn’t necessary, and the function has external linkage anyway.