Monday, 17 April 2017

How to prevent Visual C Compiler from optimizing out "unused" global variable










I have a two C files that I'm trying to compile to an executable. One file contains only a single declaration as follows (simplifed).



const char *foo[2] = {"thing1", "thing2"};


The second c file does this



extern const char *foo[2];
main()
{
//Code that does stuff with foo
}


When compiling I get a linker error that foo is an unresolved external symbol. I'm assuming the compiler is optimizing out foo. Any ideas here?


Answer



There's nothing wrong with your declarations. The code should compile and link as is, assuming you add explicit int as the return type of your main. The only explanation for the linker error I can come up with is that you are forgetting to supply all required object files to the linker.



The answers that attempt to explain this issue through the fact that in C++ const objects have internal linkage are misleading and irrelevant. The above object foo is not a const object.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...