main
的参数argc
和argv
用作向程序发送参数的方式,可能最熟悉的方式是使用Good Ol‘终端,其中用户可以键入cat file
.这里,字cat
是获取文件并将其输出到标准输出(stdout
)的程序.
程序接收argc
中的参数数量和argv
中的参数向量,在上面的argumentcount将是2(程序名计为第一个参数),argumentvector将包含[cat
,file
,null].而最后一个元素是空指针.
通常,你会这样写:
int // Specifies that type of variable the function returns.
// main() must return an integer
main ( int argc, char **argv ) {
// code
return 0; // Indicates that everything went well.
}
如果您的程序不需要任何参数,则以以下方式编写一个main
函数同样有效:
int main() {
// code
return 0; // Zero indicates success, while any
// Non-Zero value indicates a failure/error
}
在C语言的早期版本中,main
之前没有int
,因为这是隐含的.今天,这被认为是一个错误.
在POSIX兼容的系统(和Windows)上,存在使用包含程序environment variables的向量的第三参数char **envp
的可能性.还有main
函数的参数列表的更多变体,但我不会在这里详细说明,因为它是非标准的.
此外,变量的命名是convention,没有实际意义.坚持这一点始终是一个好主意,这样你就不会混淆其他人,但将main
定义为
int main(int c, char **v, char **e) {
// code
return 0;
}
对于第二个问题,有几种方法可以向程序发送参数.我建议你看看exec*()
family of functions,这是POSIX的标准,但它可能是easier只使用system
("command arg1 arg2")
,但使用system()
通常是不赞成的,因为它不保证在每一个系统上工作.我没有亲自测试过;但是,如果*NIX系统上没有安装bash
zsh
或其他shell ,system()
将失败.