动态库的静态成员在 Linux(GNU GCC) 上无法初始化,但在 macOS (Clang) 上可以初始化

问题描述 投票:0回答:1

看来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
c++ compiler-errors linker g++
1个回答
0
投票

在 Fedora 37 上,输出为:

$ ./a.out
print

我可以通过链接重现您观察到的行为:

g++ main.cpp -L. -Wl,--as-needed -ltest -Wl,-rpath=. -Wl,--no-as-needed

可能在Ubuntu或Debian上进行测试,其中

g++
默认配置为使用
--as-needed

© www.soinside.com 2019 - 2024. All rights reserved.