Multiple definition of main() - c

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");
}

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.

The macro substitution of onemain and twomain occurs before the compiler proper sees the program, so that doesn't make a difference. The functions are both named main.
C++ allows different functions with the same name, but does not allow two definitions of the exact same function signature. There would be no way to form a function call expression that would reach either overload. Additionally, the functions are the same entity, and one thing cannot have two definitions.
In addition, in C++ main cannot be overloaded, because the program is supposed to start when the unique main function is called, and any given system detects what format of main the particular program uses, out of a variety of allowed formats. (This auto-detection feature also applies to C.)
But you are not asking about C++; in C, without function overloading, there are no redefinitions of the same name, even for different signatures. Each name of extern linkage in C uniquely identifies an entity, so you cannot have two.
It's unclear what you want the resulting program to do. Most likely you need to build two separate programs.

I don't get what you ask - your error messages are quite clear:
You have 2 definitions of print(), which will collide. Remove one.
You as well have 2 definitions of main() - your #defines will replace your onemain and twomain functions, naming them effectively as main.

You overrode the built in print, about main, try imagining a car with two steering wheels ... it wont work ...
Your C program has two have a least one main, so the computer knows where the program starts.
If you have 2 files with two main function, then you have two different programs.

It's not possible for a C program to have more than one main() in it. Also, main() should be declared as an int and return an integer value (usually 0).

Related

void main() { } works perfectly without a header file. How can this happen ,where is the definition of main function written in C?

I wrote the following code:
void main() {
}
How can it run without any header files?
From the C Standard (5.1.2.2.1 Program startup)
1 The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
Though some compilers as for example the compiler of MS VS support the declaration of the function main with the return type void nevertheless such a declaration is not a C standard declaration of the function main.
So as the implementation declares no prototype of the function main and if the function main does not call any other function then neither header is required.
You may just write
int main( void )
{
}
The return statement also may be omitted.
Pay attention to that it is the user who defines the function main. So in the presented program above there is a definition of the function main that does not contain any statement inside its body. The function does nothing and at once returns the control to the hosted environment.
Header files are just a language feature that provides means to organize code in different modules (translation units) or even in whole libraries. They are by no means mandatory to use.
The only thing that is mandatory in a C program is to have some manner of entry point to your program. On hosted systems (such as a PC with an OS), this entry point must be a function named main(). It can be declared in several ways. void main() is not guaranteed to work unless the compiler explicitly supports that form. The most portable and standardized format is:
int main (void)
{
return 0;
}
Now of course this program is not very exciting to run, as it does absolutely nothing. But it is perfectly valid.
There need not be any forward declaration of main(). For freestanding environments, the format of the entry point is completely implementation-defined. For hosted environments, the C standard explicitly says that "The implementation declares no prototype for this function." - implementation in this case meaning the compiler. In English it means that the main() function must simply work without any previous declaration present, as per language definition.
Details regarding the various allowed forms of main().
void is a built-in type, known by the compiler. main is the entry point for a program, while printf, as you have written, needs some prototype. If you write your own printf definition in your source code, it will compile without a header.
The only thing you have to do to compile a C program is specify a entry point, i.e. main.
The headers just provide other IO possibilities.
void printf()
{
}
int main()
{
printf();
}
If you are using printf in your code without a header, the compiler doesn't know to what type of entity you are refering.
If you provide an implementation of main, the compiler knows exactly what this is meant to be, you just specified it.

Function Declaration & Definition in C for main()

I researched & understood that the standard way of creating or writing a function in C is to:
function declaration - declare the function name, arguments, and return value
function definition - define the function with the actual code implementation
function call - call or invoke the function with the name and arguments
However I'm confused about the use of the function main(). Is it allowed in C to use main() in all blocks of code i.e. using main() in declaration, using main() in definition and using main() in call.
Help please my exam is next month & I'm confused.
The function main() in C is a special function name which indicates where your program is to start, the entry point in your program for the C source code you write. Part of the C Standard Runtime is a need to know the entry point for where the C program that you are writing starts from. This is indicated with the function name main().
First you must understand that a C compiler converts the C source code text into binary object files. These binary object files are then linked together with other binary object files to produce the actual executable program. One of these types of binary object files is library files which contain the binary code of one or more functions that were previously compiled and combined into a single file.
The C compiler comes with several library files that contains functionality which you will need to complete your executable program. One of these is the C Runtime for the compiler.
When your executable program starts up, it does not start at main(). It instead starts at a special place in the C Runtime which sets up the runtime environment for your executable and then calls the main() function you provide. The main() function is where your source code starts.
As part of the C compiler there are a also include files such as #include <stdio.h> and others. These include files contain declarations for the functions of the C Standard Library such as the printf() function.
So the main() function is declared for you in the C compiler however you have to provide the actual definition of the function.
Since main() is an external label there can only be one function called main() that you define. If you have more than one definition of main() then when the linker tries to link your binary object files together into an executable, it will see the multiple main() functions and issue an error because it will not know which one to use.
One way of thinking of this is: (1) the C compiler provides the declaration for main(), (2) you provide the definition for main() and (3) the C Runtime calls your function main() as part of starting up your program.
See also What is the difference between - 1) Preprocessor,linker, 2)Header file,library? Is my understanding correct?
Function definition for main()
The standard for C indicates two different declarations for main(): int main(int argc, char *argv[]) and int main(void) (see section 5.1.2.2.1 Program startup in draft ISO/IEC 9899:TC3). See also What does int argc, char *argv[] mean?. See also the various discussions in What should main() return in C and C++?.
Some C compilers may also provide other alternatives including a wide character interface such as int wmain(int argc, wchar_t *argv[]) (see WINMAIN and main() in C++ (Extended)). C++ compilers may allow int main(int argc, wchar_t *argv[]) because C++ allows function overloading which C does not. Microsoft C++ compilers have had a variety of main() alternatives depending on whether the target program was a console application or a GUI.
The normal way of using the return value of main() is to return a value of 0 if successful and a non-zero positive number if there was an error. This was the normal and accepted behavior from the original Unix environments where programs were run in a terminal window from a command line (see Wikipedia topic Bourne Shell and Wikipedia topic Bash as well as Returning value from called function in a shell script which contains some examples of scripts) and most programs were used with command shell scripts.
Some programs use the return value to indicate the results of a test of some kind. In those cases, the value returned by main() isn't either success or an error code but instead the return value indicates some condition that a script could test for as part of carrying out its purpose. For example a program that queries an air quality indication from a sensor may return three different values indicating Good, Fair, or Poor which a script then uses to do something such as turn on a ventilation system fan at a particular speed.
Here are a couple of examples of main() definitions:
// usage: mypgm pathname
// Open the specified file and do things with the file's contents.
//
// program expects a single command line argument specifying a file.
// if pathname is not specified then it's an error.
int main(int argc, char *argv[])
{
// there is always one argument as the first argument is always
// the program name. Any additional arguments added to the
// command line begin with the second argument.
// argv[0] -> program or command name
// argv[1] -> expecting a pathname to be specified
if (argc < 2) {
printf ("Filename not specified\n");
return 1; // return non-zero indicating an error
}
// source code to do stuff with the specified file
return 0; // return zero indicating no error
}
// usage: mypgm
//
// program does not expect any command line arguments and if any are
// specified the arguments are ignored.
//
int main (void)
{
// source code to do stuff
return 0;
}
// usage: mypgm
//
// program does not expect any command line arguments and if any are
// specified the arguments are ignored.
//
// the following definition also compiles.
int main ()
{
// source code to do stuff
return 0;
}
In C you may call main recursively. You shall not declare main without its definition.
C language standard n1256
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
In C, the compiler has to know a function's return type and parameter list (if any) before it can translate a function call.
A function definition also serves as its declaration; if you define the function before it is called within the same translation unit, then you do not need to write a separate declaration for it:
void foo ( void ) // definition, also serves as declaration
{
...
}
void bar( void )
{
...
foo(); // call
...
}
Since we define foo before it's called by bar, the compiler already knows foo's return type and parameter list, so we don't need another declaration before the call in bar. However, if we were to define foo after bar, or if foo were defined in a separate translation unit (source file), then we would need a separate declaration before the call in bar:
void bar( void )
{
void foo( void ); // declaration
...
foo( ); // call
}
void foo( void ) // definition
{
...
}
main is special in that there's typically no need for a separate declaration of it in your code; you don't normally call main explicitly. It's normally called by the run time environment, which already expects main to return an int and take either zero or two parameters, like so:
int main( void );
int main( int, char ** );
Implementations may provide additional signatures for main, which they must document.
About the only place I've seen anyone call main explicitly was in the IOCCC; I've never seen a valid use case for it in production code.

Why should I declare a function in C? [duplicate]

This question already has answers here:
Must declare function prototype in C? [duplicate]
(10 answers)
Closed 7 years ago.
I have two source files test1.c and test2.c.
In test1.c:
#include <stdio.h>
void main() {
checks(); }
In test2.c:
#include <stdio.h>
void checks(){
printf("This is a sample Text");
}
In this case I can successfully build and run this program.
So why should I use:
void checks();
To declare the function?
It seems perfectly fine now.
I am Using C99.
In your case, the check() function has a very simple prototype and the default prototype applied by the C compiler is to accept anything as argument and to return an int. It is probably what is done here (except that, as you do not store the result of the function it is optimized out without noticing it).
If you want to check my theory, try to write this (and it should work until it reaches the linking phase):
int result = check();
At the end, your code work because the linker finally find something that work to plug for the check() function (yet, it should still expect an int at some point).
In fact, the declaration of a function prototype is only useful in two cases:
The code of the function and the use of the function are in the same file.
When you use the function before its declaration (code source), then you need to tell the compiler what to expect when trying to statically type the function you are writing (the compiler read a source code file from top to bottom).
For example:
int bar (int a, int b, bool c);
int foo (int a, bool b) {
int result = bar (a, a, c);
...
}
int bar (int a, int b, bool c) {
...
}
The code of the function the use of the function are not in the same file.
Then, you usually get the definition of the function through a header file which collect all the information needed by the compiler to know how to statically type your code. The header file (*.h) contains all the prototypes of the functions of the module you are using. The implementation of the functions will come after at linking time.
Note that, I usually try to avoid the first case because it is really not logical. When you read a source code, you go from top to bottom, just as the compiler do, and you expect to find the function definition before its usage... So, it is much more logical to structure your code in a way that do not need to require such artifacts. In my humble opinion...

Apparently no meaning line in a program [duplicate]

I am reading the book "Programming in C" and found in Chapter 10 an example like this:
#include <stdio.h>
void test (int  *int_pointer)
{
     *int_pointer = 100;
}
int main (void)
{
     void test (int  *int_pointer);
     int  i = 50, *p = &i;
     printf ("Before the call to test i = %i\n", i);
     test (p);
     printf ("After the call to test i = %i\n", i);
     return 0;
}
I understand the example, but I don't understand the line void test (int *int_pointer); inside of main. Why do I define the signature of test again? Is that idiomatic C?
It's definitely not idiomatic C, despite being fully valid (multiple declarations are okay, multiple definitions are not). It's unnecessary, so the code will still work perfectly without it.
If at all, perhaps the author meant to do
void test (int *int_pointer);
int main (void) {
...
}
in case the function definition was put after main ().
void test (int *int_pointer); is just a declaration (or prototype) of function test. No need of this declaration in main because you already have function definition before main.
If the definition of test were after main then it would be worth of putting its declaration there to let the compiler know about the return type, number of arguments and arguments types of test before calling it.
It's not idomatic C, but still valid.
The line is a declaration of the function test, not definition. A function can't be defined multiple times, but it's valid to have multiple declarations.
It is perfectly idiomatic C, and it actually has a (limited) practical use - although not one that is demonstrated by this example.
When you declare a function or other name at the usual global level, it is brought into scope for all function bodies in the code following the declaration. A declaration cannot be removed from a scope once it has been introduced. The function is permanently visible to the rest of the translation unit.
When you declare a function or other name within a braced block, the scope of the declaration is limited to that block. Declaring a function within the scope of another function will limit its visibility, and not pollute the global namespace or make it visible to any other functions defined in the same translation unit.
This is meaningless in the case of the example, because the definition of test also brings it into scope for all following bodies - but if test were defined in another translation unit, or even if it were defined only at the very bottom of this TU, hiding the declaration inside main would protect any other functions defined afterwards from being able to see its name in their scope.
In practical terms this is of limited use - normally if you don't want a function to be visible, you put it in another translation unit (and preferably make it static) - but you can probably contrive a situation where you might want to use this ability for constructing a module-loading system that doesn't export the original declarations of its components, or something like that (and the fact that this doesn't rely on static/separate object files might potentially have some relevance to embedded/non-hosted target environments where the linking step might not work as it does on PC, allowing you to achieve a measure of namespace protection in a purely-#include-based build system).
Example:
struct module {
void * (* alloc)(size_t);
void (* dealloc)(void *);
} loaded_module;
int main(void) {
if (USE_GC) { // dynamically choose the allocator system
void * private_malloc_gc(size_t);
void private_free_noop(void *);
loaded_module = (struct module){ private_malloc_gc, private_free_noop };
} else {
void * private_malloc(size_t);
void private_free(void *);
loaded_module = (struct module){ private_malloc, private_free };
}
do_stuff();
//...
}
// cannot accidentally bypass the module and manually use the wrong dealloc
void do_stuff(void) {
int * nums = module.alloc(sizeof(int) * 32)
//...
module.dealloc(nums);
}
#include "allocator_implementations.c"
It's not idiomatic; you typically see it in code that has problems getting their header files in order.
Any function is either used in one file only, or it is used in multiple files. If it is only used in its own file, it should be static. If it is used in multiple files, its declaration should be in a header file, and anyone using it should include the header file.
What you see here is very bad style (the function should either be static, or the declaration should be taken from a header style), and also quite pointless because the compiler can see the declaration already. Since the function is in the same file, it's not dangerous; if the declaration and function don't match the compiler will tell you. I have often seen this kind of thing when the function was in a different file; that is dangerous. If someone changes the function, the program is likely to crash or misbehave.

What are "prototypes" in a C program?

The book's I'm using to learn C explains something called "prototypes" which I couldn't understand properly. In the book, the following sample code explains these "prototypes". What does this mean here? What are the "prototypes"?
//* two_func.c -- a program using two functions in one file */
#include <stdio.h>
void butler(void);
int main(void)
{
printf("I will summon the butler function.\n");
butler();
printf("Yes! bring me some tea and writable DVD's.\n");
getchar();
return 0;
}
void butler(void) /*start of function definition*/
{
printf("You rang,sir.\n");
}
Please explain in simple terms.
Function prototypes (also called "forward declarations") declare functions without providing the "body" right away. You write prototypes in addition to the functions themselves in order to tell the compiler about the function that you define elsewhere:
Your prototype void butler(void); does all of the following things:
It tells the compiler that function butler exists,
It tells that butler takes no parameters, and
It tells that butler does not return anything.
Prototypes are useful because they help you hide implementation details of the function. You put your prototypes in a header file of your library, and place the implementation in a C file. This lets the code that depends on your library to be compiled separately from your code - a very important thing.
In this context prototype is a more generic term for what in C would be called a function declaration, i.e.:
void butler(void);
You may also find it called function signature. Both terms actually refer more to how butler() is defined from a conceptual point of view, as a function that doesn't take any argument and doesn't return a value, rather that to the fact that its declaration is enough for you to use it in your source code.
This is the prototype:
void butler(void);
Basically it defines butler as a function that takes no parameters and has no return value. It allows the compiler to continue onwards, even though the butler function has not yet really been defined. Note that the prototype doesn't contain any actual code. It simply defines what the butler function looks like from the outside. The actual code can come later in the file.
If your code had been
#include <stdio.h>
int main(void) {
butler(); // note this line
}
void butler() { return; }
The compiler would have stopped at the note this line section, complaining that butler() doesn't exist. It will not scan the whole file first for functions, it'll simply stop at the first undefined function call it encounters.
Prototype comprises the return type of a function, its name and the order of different types of parameters that you pass it.
If you write the function definition before calling the function, then a prototype is not necessary. But, as is the case in your example, the function butler() is called BEFORE its definition and so, a prototype is necessary to tell the compiler that such a function exists which will have so and so return type and parameters.
Otherwise, writing the function definition after calling the function will result in error.
void butler(void);
Is Called prototype or declaration of function.
And below is the function definition.
void butler(void) /*function definition */
{
printf("You rang,sir.\n");
}

Resources