新手上路,请教高人

hanb99 2007-04-05 09:53:30
我写了一段代码,可是无法编译,请指点一下
/*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++,挺烦的)。
...全文
223 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
freshui 2007-04-05
  • 打赏
  • 举报
回复
全局变量在cpp中写:
int a=3;
int b=4;
在外部.h如果要用就
extern int a;
extern int b;

lockhall 2007-04-05
  • 打赏
  • 举报
回复
*main.cpp*/
#include "aa.h"
#include <stdio.h>
int main(){
add();
}

中add()引用不到吧?
boxban 2007-04-05
  • 打赏
  • 举报
回复
/*aa.h*/
#ifndef AA_H
#define AA_H
//int a,b;
---> extern 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);
}
hslinux 2007-04-05
  • 打赏
  • 举报
回复
/*aa.cpp*/
#include "aa.h"
#include <stdio.h>
//int a=3;
//int b=4;
把这里的注释去了,全局变量最好在CPP里面定义
Piao_Polar 2007-04-05
  • 打赏
  • 举报
回复
g++ *.cpp -o *.exe
laiwusheng 2007-04-05
  • 打赏
  • 举报
回复
在不同的文件中用extern 声明调用避免重复声明

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧