Multiple definition of main()

jeevanreddymandali picture jeevanreddymandali · Feb 2, 2014 · Viewed 49.5k times · Source

Hi guys trying to use two main() and getting this error multiple definition of main(). I renamed my main functions then why is this error and also first defined here for my print(). header file:

#ifndef TOP_H_
#define TOP_H_

#include <stdio.h>
#include <string.h>
#define onemain main
#define twomain main
inline void print();


#endif /* TOP_H_ */

c file one:

#include "top.h"
void print();
int onemain()
{
    print();
    return 0;
}
void print()
{
printf("hello one");
}

c file two:

#include "top.h"
void print();
int twomain()
{
    print();
    return 0;
}
void print()
{
printf("hello two");
}

Error snapshot

Answer

kuroi neko picture kuroi neko · Feb 2, 2014

Basically any C (or even C++) program is a bunch of functions calling each other.
To begin a program execution, you have to pick one of these functions and call it first.
By convention, this initial function is called main.

When you include several source files in a project, the IDE compiles them all, then calls the linker which looks for one single function called main and generates an executable file that will call it.

If, for any reason, you defined two "main" functions inside all these files, the linker will warn you that it cannot choose on its own which one you intended to be the starting point of your program.