How to prevent linking of VC ++ 9 from unnecessary global variables?

I play with function level binding in VC ++. I have included / OPT: REF and / OPT: ICF , and the linker is happy to eliminate all unused functions. Not so with variables.

The following code is intended only to demonstrate the problem, I fully understand that in fact, code structured in this way is suboptimal.

//A.cpp SomeType variable1; //B.cpp extern SomeType variable1; SomeType variable2; class ClassInB { //actually uses variable1 }; //C.cpp extern SomeType variable2; class ClassInC { //actually uses variable2; }; 

All these files are compiled into the static lib library. A consumer project uses only ClassInC and links to a static library. Now comes the linker VC ++ 9.

The linker first sees C.obj referring to variable2 and includes B.obj . B.obj references variable1 , so it includes A.obj . Then begins the phase of eliminating the disordered material. It removes all functions in A.obj and B.obj , but not variables. Both variable and variable2 are stored along with their static initializers and deinitializers. This inflates the image size and introduces a delay to start the initializers and de-initializes.

The code above is simplified, in real code I really can't easily move variable2 to C.cpp . I could put it in a separate .cpp file, but it looks really dumb. Is there a better option to solve a problem with Visual C ++ 9?

+3
source share
1 answer

MSDN (see Arguments , REF | NOREF arguments, paragraph 4) indicates that You have to explicitly mark data as a COMDAT; use __declspec(selectany). You have to explicitly mark data as a COMDAT; use __declspec(selectany). for the linker to delete the specified unused data when using /OPT:REF .

Have you tried and had a chance with __ declspec (selectany) ?

+2
source

Source: https://habr.com/ru/post/1302978/


All Articles