【发布时间】:2011-08-01 04:14:44
【问题描述】:
我知道这已经被问过十亿次了,但我仍然遇到问题。
我从一个包含我所有代码的 main.cpp 文件开始。说它看起来像这样:
int a = 0;
void foo() {
a+1;
}
void bar() {
a+2;
}
int main() {
foo();
bar();
a + 3;
}
现在我想将此代码拆分为多个文件以便于管理。我希望只有一个标头header.h 和三个.cpp 文件:main.cpp、foo.cpp 和bar.cpp。
ATM,这是我的:
//header.h
int a = 0;
void foo();
void bar();
.
//foo.cpp
#include "header.h"
void foo() {a+1;}
.
//bar.cpp
#include "header.h"
void bar() {a+2;}
.
//main.cpp
#include "header.h"
int main() {
foo();
bar();
a + 3;
}
不幸的是,链接器一直在抱怨我多次定义了a。我试过使用#ifdef,但这只能防止在同一个文件中重新定义,对吗?我怎样才能做到这一点?
编辑:修改了问题,我才意识到这是多次定义的变量,而不是函数。
【问题讨论】:
标签: c++ visual-studio-2010 linker