gpt4 book ai didi

c++双重删除文件范围变量,链接问题?

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:22 25 4
gpt4 key购买 nike

我在 RHEL 6 上,gcc 版本为 4.1.2。

我面临着与这篇文章中描述的完全相同的问题。唯一的区别是我面临文件范围变量的这个问题。 (在类外部但在文件中声明的变量,因此它可以跨两到三个函数访问。即使我在堆栈上声明,这个变量也会被双重删除)

c++ linux double destruction of static variable. linking symbols overlap

在我的申请中,我有类似的情况。

static library "slib"
-- inside this library, there is static object "sobj"
dynamic library "dlib"
-- links staticly "slib"
executable "exe":
-- links "slib" staticly
-- links "dlib" dynamicly

我怀疑,我也面临着同样的问题。为了验证,我需要提出 g++ 命令,它将以上述方式构建文件。我尝试执行以下命令,但它不会重现上述行为。

g++ -Wall -c static_lib.cpp
ar -cvq libtests.a static_lib.o

g++ -Wall -fPIC -c dynamic_lib.cpp
g++ -shared -Wl,-soname,libtestd.so.1 -o libtestd.so.1.0 dynamic_lib.o -L. libtests.a
ln -s libtestd.so.1.0 libtestd.so

g++ -Wall -I. -L. main_exe.cpp -ltestd -ltests -o main_prog

我不确定我是否已正确或按要求的方式链接文件。但它并没有产生我想观察的缺陷。例如,我的可执行版本输出以下数据。

user:~/problem$ ./main_prog
CTest() this=134520880
use
use
~CTest() this=134520880, is Alive

其中使用cmake生成make文件,输出如下数据。

user:~/problem$ ./main_exe 
CTest() this=134520880
CTest() this=134520880
use
use
~CTest() this=134520880, is Alive
~CTest() this=134520880, is Dead

能否请您帮忙实现同样的效果。我试过运行 makefile -n 来打印命令,但它不会打印所有命令并在构建动态库后停止。

任何输入都将受到赞赏。更新:我使用了“make VERBOSE=1”并观察了后续命令的执行情况。我不知道为什么使用 -rdynamic 但我们在我们的应用程序中使用相同的。请在下面找到正在执行的命令。

/usr/bin/c++    -fPIC -c static_lib.cpp
/usr/bin/ar cr libstatic_lib.a static_lib.o
/usr/bin/ranlib libstatic_lib.a
/usr/bin/c++ -fPIC -c dynamic_lib.cpp
/usr/bin/c++ -fPIC -shared -Wl,-soname,libdynamic_lib.so -o libdynamic_lib.so dynamic_lib.o libstatic_lib.a
/usr/bin/c++ -fPIC -c main_exe.cpp
/usr/bin/c++ main_exe.o -o main_exe -rdynamic libstatic_lib.a libdynamic_lib.so -Wl,-rpath,/home/amey/c_examples/cmake

此外,nm 测试显示该符号具有不同的值。

desktop:~/c_examples/cmake$ nm libdynamic_lib.so |grep _ZN5CTest4testE
0000000000201048 B _ZN5CTest4testE
desktop:~/c_examples/cmake$ nm main_exe |grep _ZN5CTest4testE
0000000000602048 B _ZN5CTest4testE
desktop:~/c_examples/cmake$ nm libstatic_lib.a |grep _ZN5CTest4testE
0000000000000000 B _ZN5CTest4testE

所以有两个主要问题在我脑海中萦绕?1)为什么有两个构造函数?即使有两个构造函数为什么它们指向同一个对象2)是否存在编译顺序问题?

最佳答案

要获取 cmake 执行的命令列表,请运行 make clean && make -DVERBOSE=1 或在环境中设置 VERBOSE,希望有助于重复问题。要回答为什么变量被双重初始化/销毁,数据太少了。

关于c++双重删除文件范围变量,链接问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com