新手上路,请教高人

hanb99 hanb99 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我写了一段代码,可是无法编译,请指点一下
/*main.cpp*/
#include "aa.h"
#include <stdio.h>
int main(){
add();
}

/*aa.h*/
#ifndef AA_H
#define AA_H
int a,b;
void add();
#endif

/*aa.cpp*/
#include "aa.h"
#include <stdio.h>
//int a=3;
//int b=4;
void add(){
printf("+++++++++%d\n", a+b);
}
我的想法是将变量、函数的声明与实现分开,所以将它们写成了两个文件,但是我遇到一个问题,就是如上的写法会编错误,过程如下:
g++ aa.h aa.cpp -c //通过
g++ main.cpp -c //通过
g++ main.o aa.o //报错
aa.o:(.data+0x0): multiple definition of `b'
main.o:(.data+0x0):第一次在此定义
aa.o:(.data+0x4): multiple definition of `a'
main.o:(.data+0x4):第一次在此定义
collect2: ld 返回 1
只有在将aa.h 文件中的变量声明去掉,在aa.cpp中添加(就是被注释的)才能通过,难道是因为我在两个cpp文件中同时引用了aa.h文件造成了变量重复定义(可是我有写#ifndef AA_H呀)?另外有没有简单的编译方法(要写三次g++,挺烦的)。
...全文
评论 6
收藏 已收藏
分享
返回顶部
hanb99
新手乐园 33,314 成员 41,769 内容