为什么不使用共享库符号中定义的符号?

时间:2013-07-24 13:43:45

标签: c++ c shared-libraries inline

我有一个非常简单的共享库,有两个函数。 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)如果原因是编译器内联函数(即为短?),我该如何避免这种行为?我已经尝试了以下方法(和组合)并没有取得多大成功......虽然我不放弃我做错了什么:

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

    void hello2() __attribute__ ((noinline));

    void hello2() {
      asm("");
      std::cout 
  • Add the flag -fno-default-inline in the compiler flags.
  • Add asm(""); in the hello2() definition to simulate a side-effect.

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"

asm("");

1 个答案:

答案 0 :(得分:2)

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

相关问题