执行C ++程序的命令行参数

0 c++ linux command-line

这是我的c ++程序的主要内容:

void main(int argc, char** argv, Arguments& arguments)
Run Code Online (Sandbox Code Playgroud)

第一个参数是一个文件,其余参数是布尔值。
我想知道命令行编译程序的正确语法是什么。
我试过了:

gcc  -o "argument1" "argument2" "argument3" prog.cpp  
Run Code Online (Sandbox Code Playgroud)

g++ -std=c++11 -o "argument1" "argument2" "argument3" prog.cpp
Run Code Online (Sandbox Code Playgroud)

但是我得到这个错误:

linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)

我怀疑我没有正确传递参数,因此我的程序未正确链接到输入文件(argument1)。
谢谢你纠正我。

Pau*_*ger 7

主参数和命令行参数

Main可以具有以下两种形式之一

int main()
int main(int argc, char** argv)
Run Code Online (Sandbox Code Playgroud)

在第一种形式中,您不能传递任何参数。第二种形式argc是对在命令行上传递的参数的计数,并且argv是包含命令行参数char*的长度(c样式字符串)的数组argc

因此,例如,如果您将程序调用为

./program apple bananna carrot date
Run Code Online (Sandbox Code Playgroud)

然后argc等于5,argv并将包含以下值:

argv[0] = "./program" -- the name of your program as called on the command line. 
argv[1] = "apple"
argv[2] = "bananna"
argv[3] = "carrot"
argv[4] = "date"
Run Code Online (Sandbox Code Playgroud)

编译并运行程序

C ++不是一种解释性语言,因此必须进行编译。假设您的源代码位于名为的文件中program.cpp,并且希望program调用可执行文件,则可以g++按以下方式调用:

g++ -o program program.cpp
Run Code Online (Sandbox Code Playgroud)

如果ls是当前目录,现在应该program在源代码旁边的目录中看到一个名为的文件。现在,您可以运行该程序(同样,假设您将输出文件命名为program

./program arg1 arg2 arg3
Run Code Online (Sandbox Code Playgroud)

以及字符串arg1arg2arg3将如上所述传递到main中。


mat*_*ule 6

main 函数定义如下:

int main (int argc, char *argv[])
Run Code Online (Sandbox Code Playgroud)

或者

int main (int argc, char **argv)
Run Code Online (Sandbox Code Playgroud)

据我了解,argc = Argument Count 和 argv = Argument Vector。argc 是参数的数量(您可以选择多少),而 argv 包含该数量的参数,其中包含您要从命令行传递给程序的所有实际数据。但请记住,至少有一个参数排在第一位:程序的名称。

这些不是在编译期间使用,而是在运行时使用。运行程序与编译和链接不同,编译和链接必须首先完成(在您的情况下使用 gcc)。