[英]Linking to static C++ library on Mac OS X: global object constructor from library is not called
[英]Static object not initialized on Mac OS X
//File A.h containing class A
//DLL or dylib code.
class A {
//Class methods
A ()
{
count = 5;
}
//Append is running fine as it is tested
A& Append (const A& a)
{
//Append operation.
str = str + a.str;
return *this;
}
//this is running fine in all other cases except for this static object.
A& operator= (const A& a)
{
//Statement 1
str = a.str;
//Problem is faced in the statement 1 on the assignment of str to a.str
//I forget to add this code.
count = a.count;
return *this;
}
private:
std::string str;
int count;
};
//File B.cpp in some other layer
//When these variables in dylib.
static A obj1;
static A obj2;
static void f ();
static void g ();
//This Initialize is called whenver DLL or dylib is being loaded.
Initialize ()
{
f();
g();
}
//Problem faced in a function f
void f ()
{
A a;
//Some operation performed on a
a.Append (GetA("String"));
//Here I am facing problem of Bad memory access possibly over statement 1.
obj1 = a;
//Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}
void g ()
{
A a;
//Some operation performed on a
//Here I am facing problem of Bad memory access possibly over statement 1.
obj2 = a;
//Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}
//The application An exe or .app on Mac OS X
int main ()
{
InitializeApplication ();
void * handle;
//Dynamic library is being loaded.
handle = dlopen("mylib.dylib", RTLD_LAZY);
//Functions are being loaded.
f1 = dlsym(handle, "MyFunction");
//Rest of the code.
}
當我在Windows上運行類似程序(使用cl編譯器編譯)時,值obj1.count和obj2.count為5(由默認構造函數初始化)。
但是,當我在Mac OS X(使用clang編譯器編譯)上運行此程序時,obj1.count和obj2.count的值為0。
我缺少初始化類的靜態對象的東西嗎? 如果有陣列,需要執行哪些步驟?
在我的程序中,有一個應用程序在加載dylib(在Mac OS X上)或DLL(在Windows上)。 此代碼是共享庫或DLL的一部分。
靜態對象obj1和obj2在DLL中。 此DLL被加載,然后調用。
在Windows中觀察到以下行為
在Mac OS X上
在Mac OS X上,對象中的所有內容均由零初始化。 每個地址均為NULL。
但是,當我將這些變量移到靜態庫(此dylib鏈接到該靜態庫)時,一切都按照預期運行。
dylib中是否存在全局/靜態對象問題?
由於您:
A& operator= (const A& a)
{
//Statement 1
str = a.str;
}
不復制count
,那么我們可以期望復制對象中count
“不確定”值。 詛咒可能是5
,但還有其他一些價值。 operator=
應該復制(或初始化)該類的所有內容。
編輯:並且您應該有return *this;
也在那里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.