Mark
Mark

Reputation: 8678

Why is initializing this way in C giving multiple definition error?

Below are two files which I will use as my example. If I define an array of structures in file1.h and have file2.c include file1.h I would get a multiple definition error. Why is that? If I just have struct thread tasks[32] I don't get this error.

file1.h

...
...
struct thread tasks[32] = {0}; // thread is structure defined above
...
...

file2.c

#include file1.h

Upvotes: 1

Views: 1243

Answers (3)

SpacedMonkey
SpacedMonkey

Reputation: 2773

You can prevent problems from multiple includes by wrapping the contents of your header files in #ifndef like this

/* file1.h */
#ifndef INCLUDE_FILE1
#define INCLUDE_FILE1

/* contents here */

#endif

Upvotes: 1

ecatmur
ecatmur

Reputation: 157344

The = {0} turns the line from a declaration into a definition. You can have as many (compatible) declarations of a file-scope variable as you like, but at most one definition; by including the header in multiple source files you are causing multiple definitions to be generated.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

Most likely you are including the header file in more than one source file. The #include directive literally includes the contents of the header file into the source file, which means that all code in the header file will also be in the source file. This means that if two or more source file includes the same header file then the code in the header file will be duplicated.

Upvotes: 2

Related Questions