开发者社区> 问答> 正文

GCC报错multiple definition of ***,可明明加了宏定义?报错

main.cpp


#include <iostream>
using namespace std;
#include "testcpp.h"

int main() {
	int q = AddCpp(1, 2);
	q++;
#if __cplusplus
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
#endif
	return 0;
}


testcpp.h

#ifndef TESTCPP_H_
#define TESTCPP_H_

int m_ParamCpp;
int AddCpp(int a, int b);

#endif /* TESTCPP_H_ */



testcpp.cpp

#include "testcpp.h"


int AddCpp(int a, int b)
{
	m_ParamCpp++;
	return a + b;
}



eclipse cdt + Mingw gcc编译的,报错“Main.cpp: multiple definition of `m_ParamCpp'”和“testcpp.cpp:5: first defined here”,我在testcpp.h中已经加了宏定义避免头文件重复包含,怎么会这样?谁能跟我解释一下?

展开
收起
爱吃鱼的程序员 2020-06-14 20:25:50 1254 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    在main.cpp中包含一次,在testcpp.cpp包含一次,当然就两次了。

    避免头文件重复只是在一个文件中防止这个头文件被包含两次,并不能防止它被包含在两个不同的文件中。

    好吧,感觉应当就是因为这个,居然有点转不过弯来了哈。这个正解。把变量改成static的,gcc编译的时候每个cpp文件都是独立编译的,比如main.cpp会生成main.o,testcpp.cpp会生成testcpp.o,这个时候两个.o文件中都有m_ParamCpp的定义,所以会重复头文件中用extern声明一下定义放在cpp中extern int m_ParamCpp;在main.cpp或者test.cppintm_ParamCpp;
    2020-06-14 20:26:08
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Decian GNU/Linux安全合规之路 立即下载
Debian GNU/Linux 安全合规之路 立即下载
低代码开发师(初级)实战教程 立即下载

相关镜像