我有一个非常简单的共享库,有两个功能。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) 4.1.2
1)为什么我会有这种行为?
2)我如何更改 Makefile 或标题(但不是 .cpp),以便只需要重新编译库以使更改生效。
3)如果原因是函数被编译器内联(即简短?),我怎样才能避免这种行为?我已经尝试了以下方法(和组合)但没有取得多大成功......虽然我不放弃我做错了什么:
- 在 lib.hpp 中添加 __attribute__ ((noinline)) (仅限 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"
#include <iostream>
void hello1() {
std::cout << "hello1(): second implementation" << std::endl;
}