转:c++局部变量

开始错误的做法

在global.h声明并定义变量

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int sharedData = 9;  
编译出错
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Building target: CTest  
  2. Invoking: GCC C++ Linker  
  3. g++  -o "CTest"  ./src/CTest.o ./src/global.o     
  4. ./src/global.o:(.data+0x0): `sharedData'被多次定义  
  5. ./src/CTest.o:(.data+0x0):第一次在此定义  
  6. collect2: 错误: ld 返回 1  

正确的做法,

在global.h头文件声明

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. extern int sharedData ;  


在global.cpp定义初始化

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int sharedData = 9;  

然后在其他文件直接调用就可以了

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int main(void)  
  2. {  
  3.     cout<<sharedData<<endl;  
  4.   
  5. return 0;  
  6. }  

貌似在调用之前声明一下也可以。

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. extern int sharedData ;  

看一下编译

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. make all   
  2. Building file: ../src/CTest.cpp  
  3. Invoking: GCC C++ Compiler  
  4. g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/CTest.d" -MT"src/CTest.d" -o "src/CTest.o" "../src/CTest.cpp"  
  5. Finished building: ../src/CTest.cpp  
  6.    
  7. Building file: ../src/global.cpp  
  8. Invoking: GCC C++ Compiler  
  9. g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/global.d" -MT"src/global.d" -o "src/global.o" "../src/global.cpp"  
  10. Finished building: ../src/global.cpp  
  11.    
  12. Building target: CTest  
  13. Invoking: GCC C++ Linker  
  14. g++  -o "CTest"  ./src/CTest.o ./src/global.o     
  15. Finished building target: CTest  


第一步

CTest.cpp编译为CTest.o  此处其实用到了global文件的变量,由于此阶段只需要包含头文件,让CTest.cpp知道global文件变量的声明即可。


第二部

global.cpp编译为global.o


第三部

链接CTest.o和global.o  ,生成可执行文件CTest。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值