Home > Software engineering >  Can I safely use functions containing "main" in their name besides "int main(int argc
Can I safely use functions containing "main" in their name besides "int main(int argc

Time:11-26

Recently I came across this micro article where the following is stated:

  1. In your C program, you can have only one "main" function, whether it is called "main" or otherwise. If you use IPA, IPA will terminate with an error message issued when more than one "main" function is detected.

Do I understand correctly that the main name (or some other name which is explicitly defined as a replacement of int main() for an entry point) is an important part and, for example, I can have int main(int argc, char **argv) and int sub_main(int argc, char **argv) at the same program?

If not, and if there is a main as part of the functions' names and/or (int argc, char **argv) as parameters I might have a problem, will changing the places of the parameters to int sub_main(char **argv, int argc) make any difference?

I haven't had problems so far so assume int main(int argc, char **argv) and int sub_main(int argc, char **argv) can happily coexist. Still, might be handy to know for sure.

CodePudding user response:

According to the C standard, you must have one and only one main function in your code, and this is where execution starts from. C defines the following declarations only :

  • int main(void)
  • int main(int, char **) (or equivalent, say char *argv[])

There may also be (as with any C function, only one definition of this, among all files (but there may be any number of declarations).

sub_main() or any other variant that is not exactly main() is perfectly legal. A function's name and its type are distinct - names are unique, types needn't be.

So for void fn(void);, fn is the "name" (also called "identifier"), while void (void) is the type (function that takes no parameters and returns nothing).

When you wish to know for sure, be sure to ask others , like you did here, but also be sure to correlate people's answers with the C standard where it matters.

CodePudding user response:

Only the exact name of the function "main" is important fot the compiler to know where the program starts.

  • Related