什么是编译和运行 C++ 程序的命令?

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.cppor来确保您在同一目录中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以运行编译后的代码。

  • 编译器通常使二进制文件(在本例中为`a.out`)可执行。如果没有,你可以输入:`chmod +x a.out`。当你编译的程序可执行时,你可以运行它,输入`./a.out` - 点和斜线指示,你想执行它。 (6认同)

小智 23

我在这里做两个假设:

  1. 您已经准备好构建 C++ 源文件/程序
  2. 您已在计算机上设置了构建系统

在 Ubuntu 或任何其他 Linux 发行版上编译 C++ 程序的最简单方法是键入

g++ main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
  • g++GCC的 C++ 组件的调用,它是 C/C++ 和 Linux 平台上所有其他语言的事实上的编译器。它是目前唯一能够编译 Linux 内核的编译器。
  • main.cpp是您要编译的 C++ 源文件。
  • -o main指定您希望在编译源后创建的输出文件的名称。如果您愿意,目标源文件和目标输出文件可以反转,因此g++ -o main main.cpp同样有效。
  • 然后执行该程序,您需要在终端中执行 ./main 。

上述命令假设您已经在源文件所在的位置,但源文件和目标输出文件也可以指定为目录。例如

g++ ~/Desktop/main.cpp -o ~/Projects/main
Run Code Online (Sandbox Code Playgroud)

将编译位于桌面上的 C++ 源文件,并将可执行二进制Projects文件放在主目录的文件夹中。要运行此可执行文件,请运行./Projects/main.


amr*_*mrx 6

这就是我喜欢用 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)