__decspec(selectany)

我们在使用宏定义一类的技术时,容易发生符号的重定义,特别在这个符号是全局变量时。

可以使用__decspec(selectany)提示编译器,可以重定义此符号。

1.cpp

int sym = 1;

int main()

{

...

}

2.cpp

int sym = 1;

void function()

{...}//only used to prompt the sym is global symbol 

编译器会提示,符号重定义。


我们两种解决方案:

1.cpp

int sym = 1;

int main()

{

...

}

2.cpp

extern int sym;

void function()

{...}//only used to prompt the sym is global symbol 

第一个方法就是不要重定义咯~


1.cpp

extern __declspec(selectany)  int sym = 1;

int main()

{

...

}

2.cpp

extern __declspec(selectany) int sym = 1;

void function()

{...}//only used to prompt the sym is global symbol 

这个时候编译器会任选一个sym的定义作为sym的定义语句。

所以,我们通常这么也这么定义:

extern const __declspec(selectany) int sym = 1;

以上

原文地址:https://www.cnblogs.com/wangpei0522/p/4801714.html