C++无法执行二进制文件

C++ cannot execute binary file

我刚刚使用 g++ 编译了我的源代码:

g++ -o exec Test.hpp

这不会生成可执行文件,即使我使用 chmod 使其可执行,我也会收到此错误。

bash: ./exec: cannot execute binary file: Exec format error

这是我的来源:

#include <iostream>

class Test {

  void main() {
    std::cout << "testing" << std::endl;
  }
};

我使用的是 Manjaro,它不是虚拟机。 有什么建议吗?

GCC 通过扩展名识别文件的 content/type,并且“.hpp”被假定为头文件(1)。编译头文件会生成一个预编译头文件,该文件是二进制且不可执行的。

解决方法是将文件重命名为“.cpp”(2)或添加“-x c++”

g++ -o exec Test.cpp
g++ -o exec -x c++ Test.cpp

(1) 参见 https://gcc.gnu.org/onlinedocs/gcc-3.0/gcc_3.html#SEC5 "For any given input file, the file name suffix determines what kind of compilation is done:"

(2) 或任何 .cc、.cp、.cxx、.cpp、.c++ 或 .C,参见 (1)