115 command-line programming c++
我是 Linux 新手。我使用的是 Ubuntu 11.04,不知道如何在其中编译和执行 C++ 程序。我需要知道在 Linux 中编译和执行C++ 程序的命令。
bel*_*qua 142
要编译您的 C++ 代码,请使用:
g++ foo.cpp
Run Code Online (Sandbox Code Playgroud)
示例中的foo.cpp是要编译的程序的名称。
这将在同一目录中生成一个可执行文件a.out
,您可以通过在终端中键入以下内容来运行它:
./a.out
Run Code Online (Sandbox Code Playgroud)
g++应该已经在你的 $PATH 中,所以你不需要/usr/bin/g++
显式调用,但你可以在任何情况下使用后者。
foo.cpp
应该在您运行命令的同一目录中。如果有任何疑问,您可以通过键入ls foo.cpp
or来确保您在同一目录中head foo.cpp
(如果您需要验证您使用的是正确的foo
.)
正如@con-f-use 所指出的,编译器通常会使此文件可执行,但如果不是,您可以自己执行此操作(因此要执行的命令./a.out
或等效命令将起作用):
chmod +x ./a.out
Run Code Online (Sandbox Code Playgroud)
指定编译输出文件的名称,使其不被命名 a.out
,请-o
与您的 g++ 命令一起使用。
例如
g++ -o output foo.cpp
Run Code Online (Sandbox Code Playgroud)
这将编译foo.cpp
为名为 的二进制文件output
,您可以键入./output
以运行编译后的代码。
小智 23
我在这里做两个假设:
在 Ubuntu 或任何其他 Linux 发行版上编译 C++ 程序的最简单方法是键入
g++ main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
g++ -o main main.cpp
同样有效。上述命令假设您已经在源文件所在的位置,但源文件和目标输出文件也可以指定为目录。例如
g++ ~/Desktop/main.cpp -o ~/Projects/main
Run Code Online (Sandbox Code Playgroud)
将编译位于桌面上的 C++ 源文件,并将可执行二进制Projects
文件放在主目录的文件夹中。要运行此可执行文件,请运行./Projects/main
.
这就是我喜欢用 g++ 编译的方式。
$g++ -W -Wall -pedantic -o programName -p sourceFile.cpp
-W: Print extra warning messages for some problems.
-Wall: Enable all the warnings about questionable code
-pedantic: Show all the warnings demanded by strict ISO compliance
-o programName: place the executable output in programName sourceFile.cpp: the
name of our source code file
-p: Generate extra code to write profile information suitable for the analysis program prof
Run Code Online (Sandbox Code Playgroud)