gpt4 book ai didi

c++ - 为什么共享库符号中定义的符号没有被使用?

转载 作者:行者123 更新时间:2023-11-30 18:58:10 27 4
gpt4 key购买 nike

我有一个非常简单的共享库,有两个函数。 hello1() 在 lib.cpp 文件中定义,而 hello2() 在头文件 (lib.hpp) 中定义。 hello1() 和 hello2() 未声明为内联。

然后我有一个测试程序,其中包括共享库的 header 和针对共享库的链接。 test.cpp程序执行两个函数: #include“xdaq_headers/lib.h”

int main() {
hello1();
hello2();
}

正如预期的那样,当我更改 lib.cpp 中的 hello1() 定义并重新编译共享库时,执行测试程序时可以看到更改。

但是,如果我修改 header 中的 hello2() 定义并重新编译共享库,则这些更改在测试程序执行期间不会可见。

只有重新编译 test.cpp 后,更改才可见。

我的开发平台是:

    Linux 2.6.18-348.12.1.el5CEST 2013 x86_64 x86_64 x86_64 GNU/Linux
  • 海湾合作委员会(GCC)4.1.2

1)为什么我会有这种行为?

2) 我如何更改 Makefile 或 header (但不是 .cpp),以便只需要重新编译库即可使更改生效。

3)如果原因是该函数是由编译器内联的(即因为很短?),我怎样才能避免这种行为?我已经尝试了以下方法(和组合),但没有取得很大成功......尽管我不会放弃我做错了什么:

  • 像在 lib.hpp 中一样添加 __attribute__ ((noinline))(仅限 g++):

void hello2() __attribute__ ((noinline));

void hello2() {
asm("");
std::cout


<ul>
<li>Add the flag -fno-default-inline in the compiler flags.</li>
<li>Add <code>asm("");</code> in the hello2() definition to simulate a side-effect.</li>
</ul>

<p>lib.hpp:</p>

<pre><code>#ifndef _mylib_lib_hpp_
#define _mylib_lib_hpp_

#include <iostream>

void hello1();

void hello2() {
std::cout << "hello2(): first implementation" << std::endl;
}

#endif
</code></pre>

<p>lib.cpp:
#include "xdaq_headers/lib.h"</p>

#include <iostream>

void hello1() {
std::cout << "hello1(): second implementation" << std::endl;

}

最佳答案

因为 hello2 是在 header 中定义的,所以您的测试程序将使用它而不是共享库的版本。因此,如果修改头文件,则需要重新编译测试程序。如果您希望能够重新编译共享库,则需要将 hello2 的定义(即代码)从 header 移出并移至其他 cpp 文件中。

关于c++ - 为什么共享库符号中定义的符号没有被使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835820/

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