开发者

Create and use a header in C++

I've got three files, add.h, add.cpp and test.cpp

add.h creates a header for a class, and is nothing but skeletons for implementation later.

add.cpp contains the actual code for the class listed in add.h

test.cpp contains the main method and declares an instance of the class in add and uses some of its methods.

However, I'm having trouble compiling it. In add.h, I have #DEFINES to prevent mul开发者_运维百科tiple writes of the header, and in add.cpp and test.cpp I have add.h included, but when I attempt to compile using the line

g++ test.cpp -o test

I get an error about undefined references to the class objects and methods in add.h. I've been searching google on how to compile or run this, but so far no help, can StackOverflow help me?

EDIT: Sorry, I should have also included that I did try g++ test.cpp add.cpp -o test and it didn't work either, yielding the same resulting errors.


Compile each file separately, then link:

g++ -Wall -c test.cpp
g++ -Wall -c add.cpp
g++ -o test test.o add.o

Or compile and link all files in one command:

g++ -Wall -o test test.cpp add.cpp


run g++ test.cpp add.cpp -o test

EDIT: copypasted my comment here

You need to understand why your initial approach isn't working. When you reference stuff from add.h header in test.cpp, the compiler looks for definitions, but does not find them, because they are in add.cpp and you did not pass it to the compiler. The compiler can't just guess that it should look for the definitions in the add.cpp file just because you included add.h in test.cpp.


run g++ test.cpp add.cpp -o test

or

g++ -c add.cpp -o add.o
g++ -c test.cpp -o test.o
g++ test.o add.o -o test

the -c flag tells gcc to just compile and not link the first two steps compile 1 cpp (a compilation unit) in an object file the last step links those into a single executable

your actual problem comes from the fact that when you compile test.cpp, it refers to some simbols which are undefined. If you're just compiling (-c flag) that's fine, and the next step is to link with those objects file containing the missing symbols.


You need

 g++ test.cpp app.cpp -o myTest

as app.cpp contains code used by test.cpp.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜