vda8888
vda8888

Reputation: 707

C include error multiple definition error

I'm encountering a classic error but still don't get why it occurs...

Below is the simplified explanation Apparently I have two C files main.c and support.c

in support.c i have one function void bla(int input);

in main.c i have several functions using bla from support.c, and i included

#include<support.c> 

at the top of main.c

However I cannot compile the project because of the error multiple definition of bla, first defined here (eclipse points to the definition of bla in support.c)

I know that optimally I would have to create header file support.h and gives prototype extern void bla(int input) there, but for this I have to include the .c file.

Thanks in advance.

Upvotes: 0

Views: 2026

Answers (3)

user10563085
user10563085

Reputation:

What compiler are you using?

When compiling, make sure you do this:

gcc main.c support.c -o yourProgram

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You don't include source files into other source files. Instead you make a header file (with the extension .h) that contains declarations of functions, i.e. function prototypes. Then you build both source files separately, and link them together to form the final executable.

So a header file support.h like

#ifndef SUPPORT_H
#define SUPPORT_H

void blah(void);

#endif

(The preprocessor #ifdef/#define/#endif things are for include guards, to protect from multiple inclusion in the same source file.)

Then the support.c source file

#include "support.h"

void blah(void)
{
    /* Some code here... */
}

And finally the main.c source file

#include "support.h"

int main(void)
{
    blah();
    return 0;
}

If you have an IDE (like Visual Studio) if you add these files to your project the IDE will make sure everything is built and linked properly. If you're compiling on the command line, compile each source file into an object file (usually using an option like -c (used for GCC and clang)) and then link the two object files together to create the executable.


Command line example with GCC:

$ gcc -Wall -c main.c -o main.o
$ gcc -Wall -c support.c -o support.o
$ gcc main.o support.o -o my_program

The above three commands will first compile the source files into object files, and then link them together.

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122383

The preprocessor will copy the contents of support.c, and paste it to main.c to replace the line #include<support.c>. So there are two definition of the function bla, one in support.c, the other in main.c.

The solution is, don't include an source file. Put the declarations of functions that you want to export in a header file support.h, and include the header file in main.c:

#include "support.h"

Upvotes: 2

Related Questions