开发者

Splitting up Code into Multiple Files

I know this has been asked a billion times before, but I'm still having trouble.

I began with one main.cpp file that contained all of my code. Say it looked like this:

int a = 0;
void foo() {
    a+1;
}

void bar() {
    a+2;
}

int main() {
    foo();
    bar();
    a + 3;
}

Now I want to split up this code into multiple files for easier management. I would like to only have one header, header.h, and three .cpp files: main.cpp, foo.cpp, and bar.cpp.

ATM, this is what I have:

//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;
}

Unfortunately, the linker has been complaining that I've defined a m开发者_Go百科ultiple times. I've tried using #ifdef, but that only guards against redefining in the same file, correct? How can I make this work?

EDIT: Modified the question, I just realized that it is the variables that have been defined multiple times, not the functions.


I think the bigger problem is you are implementing something in a header file. The problem is when you include the header into more than one object file, you will run into problem at linker time. Don't do it.

Use a define for this sort of thing. They difference is that a define, being a preprocessor macro, doesn't create any object code by itself, and won't create any symbols. There are advantages to declaring some sort of const type instead of a define, but I think not having to worry about symbol collisions at link time is a bigger benefit.

Your header file needs include guards, as well


//header.h
void foo();
void bar();

should be

extern void foo();
extern void bar();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜