![gcc编译的Hello World c++的执行格式错误](https://linux22.com/image/877303/gcc%E7%BC%96%E8%AF%91%E7%9A%84Hello%20World%20c%2B%2B%E7%9A%84%E6%89%A7%E8%A1%8C%E6%A0%BC%E5%BC%8F%E9%94%99%E8%AF%AF.png)
在 AWS Ubuntu Server 上,我编写了 C++ Hello, World 程序:
#include <iostream>
using namespace std;
int main(){
cout<<"Hello, World!"<<endl;
return 0;
}
并编译它:
ubuntu@ip-xxxxx:~/dev/c++$ g++ -c ./test.cc -o out
ubuntu@ip-xxxxx:~/dev/c++$ chmod a+x out
ubuntu@ip-xxxxx:~/dev/c++$ ./out
-bash: ./out: cannot execute binary file: Exec format error
ubuntu@ip-xxxxx:~/dev/c++$ file ./out
./out: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
ubuntu@ip-xxxxx:~/dev/c++$ uname -a
Linux ip-xxxxx 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@ip-xxxxx:~/dev/c++$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
看起来 x86-64 架构彼此相同。这里有什么问题?我是否必须添加更多 C++ 标志?
答案1
该-c
标志指示g++
将源代码编译为目标代码,但不要将其与必要的库链接以创建独立的可执行二进制文件。来自man 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.
要创建可执行程序,只需再次运行命令即可没有旗帜-c
:
g++ test.cc -o out
其次是
./out
(可执行标志将默认设置 -chmod
不需要明确设置)。