tags:

views:

61

answers:

3

In a C project, I have a main() function in several files. When I compile I thus have an error "multiple declarations of main". Is it possible to choose in the Makefile which one of those main() functions should be used to compile ? (the other ones would then be ignored...)

A: 

You only may have one main() function in your source. You'll have either to rename all of the other instances, or to exclude those source files that include other instances of main() from the build.

Roman D
+4  A: 

You could hide them using the pre-processor:

In file1.c:

#if defined FILE1_MAIN
int main(void)
{
  printf("Running main() in file1.c");
  return 0;
}
#endif

This can be repeated as necessary in any number of C files.

Then have logic in the Makefile that passes the proper -D option to the compiler, i.e. -DFILE1_MAIN to include the main() from file1, -DFILE2_MAIN to get file2.c's, and so on.

This technique can also be useful when implementing e.g. library modules, to include an optional main() for testing in a single C file.

unwind
Thanks, works well !
Jules Olléon
+1  A: 

You could simply write a target for each main(), where you would ignore all but one file which contains main().

Bastien Léonard