function already defined in .obj

2019-04-05 14:44发布

问题:

From what I understand, this error is caused by not properly using header guards when you have multiple files including the same file. In my case, this is the include tree that's causing the error:

File A includes Z, which contains the functions I need. File B includes A, and file C includes A.

Without any #pragma once's, The program gives a bunch of variations of the same error:

blahblah.obj: error LNK2005: class some::namespace::ObjectType Object already 
    defined in dialogDlg.obj

I just was wondering, given the include tree I described, what is the proper way to get this to compile properly?

I tried using #pragma once on file Z, but that didn't work. I also tried #pragma once on file A, which also didn't work. Finally I tried it on both A and Z, also didn't work.

回答1:

It seems you are trying to define a variable in a header file. If that header file is included in several source file it will be define in each source file thereby giving you the error.

Instead declare it as extern and then define in one of your source files.

So in the header file:

extern ObjectType Object;

And in a source file:

ObjectType Object;