开发者

macro guard doesn't work in header

开发者 https://www.devze.com 2023-02-19 16:18 出处:网络
hey everyone, i got code like this: //a.h #ifndef SB #define SB namespace A{ int a = 10; int b = 10;} #endif

hey everyone, i got code like this:

//a.h 
#ifndef SB
#define SB
namespace A{ int a = 10; int b = 10;}
#endif

however, if I imp开发者_运维知识库orted the a.h in a.cpp file, the compiler would complain:

 error LNK2005: "int A::a" (?a@A@@3HA) already defined in a.obj

It looks like compiler would combine .h file and .cpp file together without explicit "import" statement. But it doesn't make sense to me that it would happen with the macro guard defined.

I use Visual C++


#include guards prevent one file from including the same .h file multiple times. They don't prevent multiple files from each including the same .h file once, which is what I assume is happening to you. Move your definitions into a single .cpp file and leave just a declaration here:

namespace A {
    extern int a;
    extern int b;
}

which tells the compiler that these variables exist somewhere, but their definitions can be found elsewhere.


Chances are you have a cyclic #include statement some where that is putting the header file into both object files and then trying to link the object files together gets the duplicate entries.

Remember that when you #include what the compiler is doing is cut/pasting the contents of the .h file in place of the line the include is on.

You will want to declare prototypes in the .h file, not the actual declaration of those objects and their values.


If you want a and b to have constant values, you can do this:

//a.h 
#ifndef SB
#define SB
    namespace A{const int a = 10; const int b = 10;}
#endif

and it will not be a problem to include it in several places.

If you need the values to change, you should follow dfan's advice.

0

精彩评论

暂无评论...
验证码 换一张
取 消