在不改变被测对象的前提下,想要调用类的私有数据区,可以在编译测试文件时使用-Dprivate=public或者在测试文件里加#include private public
这里的被测对象可以是.cpp,也可以是已经经过编译的.o, .so文件,在编译这些文件的时候不使用-Dprivate=public,于是产生了一个疑问,public、private这些是不是只在编译阶段做检查,上网搜了下,搜到一句话:
The compiler have all information about all the code in a translation unit (a source file and all included header files), and can therefore keep track of which members are private and which are not. How the compiler does it is not relevant, and different compilers can implement it differently.
Private/public members is a pure compile-time concept, and there is nothing in the compiled executable code that enforces it.
这样就能说通为什么被测文件和测试文件里类的定义都不一样了却可以正常使用,因为函数是一样的。
破坏C++封装性如此简单(≧▽≦)/
由此又产生了个疑问:
如果在.o中函数重命名了,编译器怎么处理?
初步试验得到的结论是:
在两个.o里重定义的函数在最终生成的可执行程序里,只会有一份代码,最后谁的代码说了算,和编译时的顺序有关,谁在前就调谁。
在类中定义的函数,如果在编译的.o里没有被调用的,则不生成代码。
在类外定义的函数(包括.cpp内和.h内),无论在编译的.o中有没有调用,在代码段中都能看到代码。凌乱╭(╯^╰)╮
readelf -S 文件可以看到各个section位置,查全局变量神马的gdb一下就出来了,看汇编的时候可以用。