在 C++ 中创建并使用标头
我有三个文件,add.h、add.cpp 和 test.cpp
add.h 为类创建一个标头,只不过是稍后实现的骨架。
add.cpp 包含 add.h 中列出的类的实际代码
test.cpp 包含 main 方法并在 add 中声明该类的实例并使用它的一些方法。
但是,我在编译它时遇到了麻烦。在 add.h 中,我有 #DEFINES 来防止多次写入标头,在 add.cpp 和 test.cpp 中,我包含了 add.h ,但是当我尝试使用该行进行编译时
g++ test.cpp -o test
,出现有关未定义引用的错误add.h 中的类对象和方法。我一直在谷歌搜索如何编译或运行它,但到目前为止没有帮助,StackOverflow可以帮助我吗?
编辑:抱歉,我还应该包括我确实尝试过 g++ test.cpp add.cpp -o test 并且它也不起作用,产生相同的结果错误。
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 multiple 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
单独编译每个文件,然后链接:
或者在一个命令中编译并链接所有文件:
Compile each file separately, then link:
Or compile and link all files in one command:
运行
g++ test.cpp add.cpp -o test
编辑:在此处复制粘贴我的评论
您需要了解为什么您的初始方法不起作用。当您引用 test.cpp 中 add.h 标头中的内容时,编译器会查找定义,但找不到它们,因为它们位于 add.cpp 中,并且您没有将其传递给编译器。编译器不能仅仅因为您在 test.cpp 中包含了 add.h 就猜测它应该在 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.
运行
g++ test.cpp add.cpp -o test
或
-c
标志告诉 gcc 仅编译而不链接前两步在目标文件中编译 1 个 cpp(编译单元)
最后一步将它们链接到单个可执行文件中,
您的实际问题来自这样的事实:当您编译 test.cpp 时,它引用了一些未定义的符号。
如果您只是编译(-c 标志),那很好,下一步是链接到那些包含缺失符号的对象文件。
run
g++ test.cpp add.cpp -o test
or
the
-c
flag tells gcc to just compile and not linkthe 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.
您需要
,因为
app.cpp
包含test.cpp
使用的代码。You need
as
app.cpp
contains code used bytest.cpp
.