3

这是我没有的代码-不确定为什么会收到此错误消息:

$ ./main.cpp "hello" "is"
./main.cpp: line 4: syntax error near unexpected token `('
./main.cpp: line 4: `int main(int argc, char *argv[]){'

它在 g++ 中编译得很好,但是当我运行它时,我得到了上述错误。知道为什么吗?这是我的完整代码..

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]){

    for(int i = 0; i < argc; i++){
        std::cout << argc << " : " << argv[i] << '\n';
    }

    if (argc != 2){
        std::cout << "\nUSAGE: 2 command line arguments please." << std::endl;
        std::cout << "\n   (1) Input file with raw event scores.\n   (2) Output file to write into.";
    }

  // open the font file for reading
    std::string in_file = argv[1];
    std::ifstream istr(in_file.c_str());
    if (!istr) { 
        std::cerr << "ERROR: Cannot open input file " << in_file << std::endl;
  }

    return 0; 
}
4

3 回答 3

4

您必须运行已编译的程序,而不是源代码:

$ g++ -o main main.cpp
$ ./main "hello" "is"
3 : ./main
3 : hello
3 : is

USAGE: 2 command line arguments please.

   (1) Input file with raw event scores.
   (2) Output file to write into.ERROR: Cannot open input file hello

您的示例试图将 C++ 代码作为 shell 脚本执行,但这是行不通的。正如您从我在这里的程序测试运行的输出中看到的那样,您仍然有一些错误需要解决。

于 2013-02-06T18:54:33.987 回答
3

正如其他两个答案所说,您将其作为 shell 脚本运行,隐式使用/bin/sh.

以 开头的前两行#被 shell 视为注释。第三行是空白的,什么也不做。第四行被解释为 command int,但括号对 shell 来说是特殊的,在这里没有正确使用。您的 中可能没有int命令$PATH,但 shell 没有机会报告这一点,因为它会因语法错误而窒息。

这些细节都不是特别重要。问题是您执行的程序不正确。但是看看为什么会打印这些特定的错误消息可能会很有趣。

看来您已经做了类似的事情chmod +x main.cpp;否则shell会拒绝尝试执行它。使 C++ 源文件可执行不会造成任何真正的危害(只要它是可读和可写的),但它一点用处都没有,而且正如您所见,它延迟了对错误的检测。如果您这样做chmod -x main.cpp,然后再试./main.cpp一次,您将收到“权限被拒绝”错误。

正如卡尔的回答所说,您需要执行编译器生成的可执行文件,而不是 C++ 源文件。这就是为什么有一个编译器。编译器(嗯,实际上是链接器)将自动chmod +x对它生成的可执行文件执行等效的操作。

file命令将告诉您某些文件是什么类型的文件,这会影响您可以使用它做什么。例如,在我的系统上使用您的代码,运行后g++ main.cpp -o main

$ file main.cpp
main.cpp: ASCII C program text
$ file main
main: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xacee0dfd9ded7aacefd679947e106b500c2cf75b, not stripped
$ 

(该file命令应该识别main.cpp为 C++ 而不是 C,但有时它会猜错。)

“ELF”是我的系统使用的可执行格式;该文件包含可执行的机器代码以及一些其他信息。系统上预装的命令使用相同的格式。

细节可能在您的系统上有所不同——在非类 Unix 系统(如 MS Windows)上会有很大差异。例如,在 Windows 上,可执行文件通常以.exe扩展名命名。

于 2013-02-06T19:14:04.777 回答
0

默认情况下,编译器会创建一个名为“a.out”的可执行文件,因此您需要执行以下操作:

$ a.out "你好" "是"

键入“./main.cpp”正在尝试执行 C++ 源文件,可能作为 shell 脚本

于 2013-02-06T18:55:58.873 回答