如何使用gcc ??
将变量传递给C程序例如
gcc -o server ./server.c --host=localhost --port=1234
如何在我的代码中访问这些变量?
谢谢。
答案 0 :(得分:6)
你的问题不明确;至少有两件事你可能会问:如何在程序运行时访问传递给程序的命令行参数,以及如何在程序编译时访问传递给编译器的参数。
命令行参数:
./ server --host = localhost --port = 1234
可以通过main()
:
int main(int argc, char *argv[]) {
for (int i=0; i<argc; ++i) {
std::cout << argv[i] << '\n';
}
}
getopt
是解析这些命令行选项的一种非常常见的方法,尽管它不是C或C ++标准的一部分。
编译器参数:
您不一定能访问传递给编译器的参数,但是对于您可以检测到的参数,您可以通过更改编译环境来检测它们。例如,如果编译器选择启用语言功能,则可以通过检测功能是否已启用来检测何时传递该选项。
gcc -std = c11 main.cpp
int main() {
#if 201112L <= __STDC_VERSION__
printf("compiler was set to C11 mode (or greater).\n");
#else
printf("compiler set to pre-C11 mode.\n");
#endif
}
此外,您可以直接在程序将能够访问的编译器的命令行参数中定义宏。
gcc -DHELLO =“WORLD”main.cpp
int main() {
#if defined(HELLO)
printf("%s\n", HELLO);
#else
printf("'HELLO' is not defined\n");
#endif
}
答案 1 :(得分:0)
如果要在编译时定义它们,请参阅-D
param,如果要在运行时定义它们,请使用类似
int main(int,char**);
int main(int argsc/*argument count*/, char**argv/*argument vector*/)
{
int i;
for(i=0;i<argsc;i++)
{
printf("%s\n",argsv[i]);
}
return 0;
}
答案 2 :(得分:0)
如果要将变量传递给程序执行,可以使用环境变量。像这样:
char* myOption = getenv("MY_OPTION_NAME");
if(!myOption) myOption = "my default value";
//Do whatever you like with the value...
当您调用程序时,您可以通过在程序名称之前指定来内联设置变量:
MY_OPTION_NAME="foo" ./server
您还可以使用
一次性设置环境变量export MY_OPTION_NAME="foo"