BarberaThor
BarberaThor

Reputation: 19

Multiple includes of the same source files through a project is correct?

I'm trying to call a method in my main, which is declared in another file.

When I try to call it with this line of code in the Main.c:

#include "SPI3.c"

void main(void) {

initSpi();

}

it gives the following error:

SPI3.c:196:: error: (237) function "_initSpi" redefined

The function is declared in the file SPI3.c

void initSpi()
{
     //CODE

}

I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when you include the same file more than once and it redefines the function.

I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.

What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?

Thanks, feel free to ask for more details.

Upvotes: 0

Views: 314

Answers (2)

The_Average_Engineer
The_Average_Engineer

Reputation: 377

You should not include .c files, but .h files (except if you know exactly what you are doing).

I would rather do the following thing: in your SPI3.h file, declare your function:

void initSpi(void);

Don't forget Include guard in your .h file

and in your main.c file:

#include "SPI3.h"

Thus your function is only defined once (in your SPI3.c file), and you will not get the redefined error.

Just for clarification

When you write the following code in your .c file:

void initSpi()
{
     //CODE

}

Then you both declare and define your function.

When you write the following code in your .h file:

void initSpi(void);

Then you just declare your function. It is your function prototype.

Your function can be declared multiple times, but can only be defined once (except if using the weak keyword).

That why it is recommended to declare (and only declare) your functions in .h files and to only include those files into your .c files.

Upvotes: 1

Dr. Andrey Belkin
Dr. Andrey Belkin

Reputation: 803

By including any file, you paste its contents into your file. So, the function initSpi() is defined twice: within SPI3.c and Main.c => you get redefinition. You need to include only .h headers not .c files. These header files contain only declarations (opposed to definitions), e.g.:

/* SPI3.h */
void initSpi();

So, we include header files into our file and get declarations of functions and variables that are defined elsewhere. In order to link their definitions, we can possibly need also a Makefile or a C project file.

Upvotes: 2

Related Questions