在linux平台下,使用g++编译器编写一个动态链接库。 发现编译器对于库文件和主程序中的同名变量处理有不合理的地方。
//r6.h
#ifndef R6_H_
#define R6_H_
class r6 {
public:
r6();
void show_ood(int p,double p1);
int p2,p3=0;
virtual ~r6();
};
#endif /* R6_H_ */
//r6.cpp
#include "r6.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
double ood;
r6::r6() {
// TODO Auto-generated constructor stub
p2=2;p3=3;
}
r6::~r6() {
// TODO Auto-generated destructor stub
}
void r6::show_ood(int p,double p1)
{
cout<<p<<endl;
ood=8;
cout<<"ood="<<ood<<endl;
cout<<"the address for ood="<<&ood<<endl;
};
编译完成后,生成一个libr6.so 放置到/usr/lib 下面。
r6.h 放到/usr/include下面。
然后使用测试程序:
#include <r6.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
float ood,odd2;
int main()
{
r6 r66;
r66.show_ood(1, 2);
cout<<"in main ood="<<ood<<endl;
cout<<"in main the address for ood="<<&ood<<endl;
return 0;
}
编译通过,没有报错也没有报警。
运行结果如下:
1
ood=8
the address for ood=0x55f7391c9020
in main ood=0
in main the address for ood=0x55f7391c9020
我们会发现,ood 在库文件里面被定义,为double 在程序main里面被定义为float ,不但可以并行,还能共用同一段内存。
笔者认为,为了防止混淆,在主程序编译阶段,编译器应该要么报同名错误,要么干脆将两个ood变量隔离使用。
这样将两个变量放在一个内存里,视其为同一个变量,是不科学的。