看来gnu的链接器已经删除了
test.cpp
,因为main.cpp中没有引用。
但我确实需要在我的项目中初始化一些像这样的静态变量。
// main.cpp
#include "test.h"
int main()
{
return 0;
}
// test.h
class A
{
public:
void foo();
};
// test.cpp
#include "test.h"
#include <iostream>
auto print = []()
{
std::cout << "print" << std::endl;
return 1;
};
static int x = print();
void A::foo()
{
std::cout << "foo" << std::endl;
}
Linux 输入:
g++ -shared -o libtest.so test.cpp -fPIC -std=c++11
g++ main.cpp -L./ -ltest -o main -std=c++11
Linux 输出: (没什么)
macOS 输入:
g++ -shared -o libtest.dylib test.cpp -fPIC -std=c++11
g++ main.cpp -L./ -ltest -o main -std=c++11
macOS 输出:
print
在 Fedora 37 上,输出为:
$ ./a.out
print
我可以通过链接重现您观察到的行为:
g++ main.cpp -L. -Wl,--as-needed -ltest -Wl,-rpath=. -Wl,--no-as-needed
您可能在Ubuntu或Debian上进行测试,其中
g++
默认配置为使用--as-needed
。