-2

如何使用 gcc 将变量传递给 C 程序?

例如

gcc -o server ./server.c --host=localhost --port=1234

如何在我的代码中访问这些变量?

谢谢你。

4

3 回答 3

8

Your question isn't clear; there are at least two things you might be asking about: how to access command line arguments passed to your program when it is run and how to access arguments passed to the compiler when your program is compiled.

Command line arguments:

./server --host=localhost --port=1234

These are accessed via arguments to main():

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

getopt is a pretty common way to parse these command line options, though it isn't part of the C or C++ standards.

Compiler arguments:

You can't necessarily access arguments passed to the compiler, but for the arguments you can detect you detect them through changes to the compile environment. For example if the compiler takes an option to enable a language feature then you can detect when that option is passed by detecting if the feature is enabled.

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
}

Additionally you can directly define macros in command line arguments to the compiler that the program will be able to access.

gcc -DHELLO="WORLD" main.cpp

int main() {
  #if defined(HELLO)
    printf("%s\n", HELLO);
  #else
    printf("'HELLO' is not defined\n");
  #endif
}
于 2013-08-18T11:52:14.933 回答
0

If you want to pass variables to your program execution, you can use environment variables. Like this:

char* myOption = getenv("MY_OPTION_NAME");
if(!myOption) myOption = "my default value";
//Do whatever you like with the value...

And when you call your program, you can set the variables inline by assigning them before the program name:

MY_OPTION_NAME="foo" ./server

You could also set your environment variables once and for all using

export MY_OPTION_NAME="foo"
于 2013-08-18T16:11:58.807 回答
0

If you want to define them at compile-time see the -D param, if you want to define them at runtime use something like

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;
}
于 2013-08-18T11:54:05.077 回答