【问题标题】:Why the symbol defined in the shared library symbol is not used?为什么不使用共享库符号中定义的符号?
【发布时间】:2013-07-24 13:43:44
【问题描述】:

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

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

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

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

但是,如果我修改标头中的 hello2() 定义并重新编译共享库,那么在测试程序执行期间所做的更改将不可见。

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

我的开发平台是:

  • Linux 2.6.18-348.12.1.el5 CEST 2013 x86_64 x86_64 x86_64 GNU/Linux
  • gcc (GCC) 4.1.2

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

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

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

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

    void hello2() __attribute__ ((noinline));

    void hello2() {
      asm("");
      std::cout 
  • 在编译器标志中添加标志 -fno-default-inline。
  • 在 hello2() 定义中添加 asm(""); 以模拟副作用。

lib.hpp:

#ifndef _mylib_lib_hpp_
#define _mylib_lib_hpp_

#include <iostream>

void hello1();

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

#endif

lib.cpp: #include "xdaq_headers/lib.h"

#include 

无效你好1(){
  std::cout 
    

【问题讨论】:

    标签: c++ c shared-libraries inline


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 2016-10-16
      • 2011-07-19
      • 2021-10-21
      • 2018-04-14
      • 2019-08-30
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多