简体   繁体   English

C ++程序,用g ++编译

[英]C++ programs, compiling with g++

I am very aware of compiling C++ programs with g++ in linux environment. 我非常清楚在linux环境下使用g ++编译C ++程序。 But, may be I am missing something, I am getting this strange output/behaviour. 但是,可能是我错过了一些东西,我得到了这种奇怪的输出/行为。

I have source file in test.cpp. 我在test.cpp中有源文件。 To compile this, I did 为了编译这个,我做到了

(1)
g++ -c test.cpp 
g++ -o test test.o
./test

Everything works fine. 一切正常。 But when I did compling and linking in same stage, like this 但是,当我在同一阶段进行编译和链接时,就像这样

(2)
g++ test.cpp -o test 
./test => Works fine
(3)
g++ -c test.cpp -o test => Doesn't work

In my last case, test is generated but is no more executable; 在我的最后一种情况下,测试生成但不再可执行; but in my guess it should work fine. 但在我的猜测它应该工作正常。 So, what is wrong or do I need to change some settings/configuration ?? 那么,有什么不对或我需要更改一些设置/配置?

I am using g++ 4.3.3 我正在使用g ++ 4.3.3

Thanks. 谢谢。

When you say: 当你说:

g++ -c test.cpp -o test

The -c flag inhibits linking, so no executable is produced - you are renaming the .o file. -c标志禁止链接,因此不会生成可执行文件 - 您正在重命名.o文件。

Basically, don't do that. 基本上,不要这样做。

You are forcing compiler to produce an object file and name it like an executable. 您正在强制编译器生成目标文件并将其命名为可执行文件。

Essentially your last line tells: compile this to an object file, but name it test, instead of test.obj. 基本上你的最后一行告诉:将其编译为目标文件,但将其命名为test,而不是test.obj。

-c flag means Compile Only -c标志表示仅编译

Try g++ -o test test.cpp 试试g ++ -o test test.cpp

Specifying -o in the g++ command line tells the compiler what name to give the output file. 在g ++命令行中指定-o告诉编译器为输出文件指定的名称。 When you tried to do it all in one line, you just told the compiler to compile test.cpp as an object file named test , and no linking was done. 当您尝试在一行中完成所有操作时,您只是告诉编译器将test.cpp编译为名为test的目标文件,并且没有完成链接。

Have a look at the fabulous online manual for GCC for more details. 有关更多详细信息,请查看精彩的GCC在线手册

from the gcc manual: 来自gcc手册:

  -c Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file. 

You must link the compiled object files to get the executable file. 您必须链接编译的目标文件以获取可执行文件。 More info about compiling and linking and stuff is here . 有关编译和链接的更多信息和内容在这里

Read man g++. 阅读man g ++。 The switch -c is to compile only but not to link. 交换机-c只是编译而不是链接。 g++ -c test.cpp -o test does what g++ -c test.cpp does but the object file will be test istead of the default name test.o. g ++ -c test.cpp -o test执行g ++ -c test.cpp的功能,但是目标文件将被测试,而不是默认名称test.o. An object file cannot be executed. 无法执行目标文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM