开发者

C++ Global class variables are not created

Iam looking at a piece of code that creates global class variables. The constructors of these classes calls a symbol table singleton and ad开发者_开发问答ds the this pointers in it..

In a Keywords.cpp file

class A : class KeyWord
{
  A() { add(); }
} A def;

similarly for keywords B,C etc

void KeyWord::add()
{
 CSymbolCtrl& c = CSymbolCtrl::GetInstance();
 c.addToTable(this);
}

These translation units are compiled to form a library. When i "dumpbin" the library, i see the dynamic initializers for ADef, BDef etc.

No in the exe, when i call the CSymbolCtrl instance, i didnt find the ADef, BDef.. stored in its map. When i set a breakpoint in add(), its not getting hit. Is there a way that the linker is ignoring ADef, BDef because they are not referenced anywhere?

}


From Standard docs 1.9 Program execution,

4) This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

So, it might, yes.


The short answer is yes. A pretty common way to force registration is to do something like:

static bool foo = register_type();


It's not too clear from your question, but are you actually including the compiled object files in your link or not? Just putting a file in a library doesn't cause it to be included in the final program. By definition, a file from a library will only be included in the executable if it resolves an unresolved external symbol. If you want an object file to be part of the final executable, and it doesn't contain any globals which would resolve an undefined external, then you have several choices:

-- Link the object file directly, rather than putting it in a library. (This is the "standard" or "canonical" way of doing it.)

-- Use a DLL. Dispite the name, DLL's are not libraries, but object files, and are linked in an all or nothing way.

-- Create a dummy global symbol, and reference it somewhere. (This can often be automated, and might be the preferred solution if you're delivering a library as a third party supplier.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜