Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple definition error in .o file

Tags:

c

I have one a.h file where i have declared so many structures. I am intialising these structures in a.c file(I have included the a.h file) and i want to reuse the same a.h file in another b.c file. When i included the header file a.h in b.c i'm getting the error as multiple definition. Please help me what can be done to prevent this problem and to reuse the same .h file in both .c files.

like image 417
Angus Avatar asked Jan 16 '23 22:01

Angus


1 Answers

You must never instantiate things in header files, i.e. never define anything, just declare them.

You should put a single definition of each declared thing in one of the C files, and have extern declarations in the shared header:

In mydata.h:

struct Foo {
  float baryness;
  float baziness;
};

extern struct Foo TheFoo;

In one C file:

#include "mydata.h"

struct Foo TheFoo;

In other headers in the project:

#include "mydata.h"

printf("the baziness is %f right now\n", TheFoo.baziness);
like image 173
unwind Avatar answered Jan 26 '23 03:01

unwind