C++: having trouble linking from command line

元气小坏坏 提交于 2019-12-25 03:16:25

问题


Just getting started with C++ here. I am working on OSX with Eclipse CDT. I have a project with some custom classes and two files "Test.hpp" and "Test.cpp" - the later with my main() method that runs some tests that I have defined and implemented in these two files.

I can compile and run from Eclipse with no problems, but when I try to compile from the command line with "g++ Test.cpp" I get a lot of linking errors that basically list all the methods defined in or referenced from Test.cpp as undefined symbols.

I have compiled a few basic programs (one header file and one implementation file) in similar manner from the command line without any problems, but I can't figure out why this one won't work. Please help!

EDIT: It wasn't clear from my wording, but yes I have other source files too. The accepted answer did the trick: "g++ Test.cpp Other1.cpp Other2.cpp". Thank you.


回答1:


Command 'g++ Test.cpp' does both compilation and linking. If you have many source files, you should link Test.cpp with them too like 'g++ Test.cpp other1.cpp other2.cpp' or just compile all files and link them all together later like 'g++ Test.o other1.o other2.o'.




回答2:


Where are your files located? Is your .h file in the same directory then your .cpp file? If no: did you try with the -I option from gcc? If yes: is your working directory in the same directory then your source files?




回答3:


If you invoke G++ like that it not only compiles the code but also tries to link the results into an executable. If your test.cpp requies some functions you defined somwehere else, this explains your observations. Compilation without linking can be achieved by adding the -c switch. Alternativly you can invoke g++ with all cpp files that are needed.



来源:https://stackoverflow.com/questions/2395552/c-having-trouble-linking-from-command-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!