is there a GCC compiler/linker option to change th

2019-01-14 16:55发布

My software has one main for normal use and a different one for unit tests. I would just love it if there was an option to gcc to specify which "main" function to use.

11条回答
我命由我不由天
2楼-- · 2019-01-14 17:04

You may have to run ld separately to use them, but ld supports scripts to define many aspects of the output file (including the entry point).

查看更多
够拽才男人
3楼-- · 2019-01-14 17:04

If you use into LD "-e symbol_name" (where symbol_name is your main function, of course) you need also "-nostartfiles" otherwise error of "undefined reference to main" will be produced.

查看更多
4楼-- · 2019-01-14 17:05

The other answers here are quite reasonable, but strictly speaking the problem you have is not really one with GCC, but rather with the C runtime. You can specify an entry point to your program using the -e flag to ld. My documentation says:

-e symbol_name

Specifies the entry point of a main executable. By default the entry name is "start" which is found in crt1.o which contains the glue code need to set up and call main().

That means you can override the entry point if you like, but you may not want to do that for a C program you intend to run normally on your machine, since start might do all kinds of OS specific stuff that's required before your program runs. If you can implement your own start, you could do what you want.

查看更多
SAY GOODBYE
5楼-- · 2019-01-14 17:05
#ifdef TESTING

int main()

{

/* testing code here */

}

#else

int main()

{

/* normal code here */

}

#endif

$ gcc -DTESTING=1 -o a.out filename.c #building for testing

$ gcc -UTESTING -o a.out filename.c #building for normal purposes

man gcc showed me the -D and -U

查看更多
放荡不羁爱自由
6楼-- · 2019-01-14 17:06

I'd tend to use different files and make for testing and production builds, but if you did have a file with

int test_main (int argc, char*argv[])

and

int prod_main (int argc, char*argv[])

then the compiler options to select one or the other as the main are -Dtest_main=main and -Dprod_main=main

查看更多
甜甜的少女心
7楼-- · 2019-01-14 17:18

You can use macros to rename one function to main.

#ifdef TESTING
#define test_main main
#else
#define real_main main
#endif

int test_main( int argc, char *argv[] ) { ... }
int real_main( int argc, char *argv[] ) { ... }
查看更多
登录 后发表回答