设为首页 加入收藏

TOP

由实例浅析C中的static、extern、multiple definition of用法及陷阱
2014-11-23 19:52:19 来源: 作者: 【 】 浏览:10
Tags:实例 浅析 static extern multiple definition 用法 陷阱

在JNI中,经常会遇到这种场景:想在一个.h文件中写一些全局变量,然后所有的cpp文件都能够使用。如下有个a.h文件:

/*
 * a.h
 *
 *  Created on: 2014-4-16
 *      Author: Administrator
 */

#ifndef A_H_
#define A_H_

int mAge = 0;
void setAge(int age);
int getAge();



#endif /* A_H_ */

里面很简单,有个变量mAge,两个接口,设置和读取。

下面是a.cpp文件:

/*
 * a.cpp
 *
 *  Created on: 2014-4-16
 *      Author: Administrator
 */

#include "a.h"
void setAge(int age){
	mAge = age;
}
int getAge(){
	return mAge;
}

然后有个main.cpp文件:

//============================================================================
// Name        : Test2.cpp
// Author      : yan
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include 
  
   
#include "a.h"
using namespace std;

int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	setAge(22);
	cout<<"age = "<
   
    编译后报错:
    

E:\WorkSpaces\Eclipse_MinGW_C\Test2\Debug/../src/Test2.cpp:12: multiple definition of `main'
src\main.o:E:\WorkSpaces\Eclipse_MinGW_C\Test2\Debug/../src/main.cpp:13: first defined here
collect2.exe: error: ld returned 1 exit status
Build error occurred, build is stopped

报multiple definition of的错误,解决方法是将变量搞成static。搞成static确实不报错了,但这里却隐藏着一个天大的陷阱:

main.cpp如下:

#include 
     
      
#include "a.h"
using namespace std;

int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	setAge(22);
	cout<<"age = "<
       
         
       
<script type="text/java script">BAIDU_CLB_fillSlot("771048");
点击复制链接 与好友分享! 回本站首页
<script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
分享到: 更多
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇jspsmartupload上传下载,解决乱码 下一篇开灯问题(语言入门)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: