How to compile multiple .c and .h files in gcc linux?

So, I have a mainClass.c source, where I have a main one. I have a class1.h header file and an implementation of all the functions defined in class1.h in class1.c. I have two variables (global) in class1.h with the name cond and mutex, which are used in class1.c now and probably in the future I will use it in my mainClass.c. Now, to compile all the source files to create a single object file, I do the following:

gcc -Wall -pthread -I/home/2008/ariarad/mainClass1 mainClass1.c class1.c -o out

/ home / 2008 / ariarad / mainClass1 is where all my header files and source files are located, and I use pthead.h in one of the .c files. Although I turned it on there, he complained, so I had to turn it on.

Now, when I run the above command, I get the following errors:

class1.c:3:16: error: redefinition ofcondclass1.h:66:16: note: previous definition ofcondwas here
class1.c:4:17: error: redefinition ofmutexclass1.h:67:17: note: previous definition ofmutexwas here

Just in case, I have an ifndef and endif block surrounding class1.h to avoid multiple inclusion. I definitely do not override the variables defined in the header file in the .c file. So can someone please help me, why is he still giving me errors?

+5
source share
1 answer

You cannot define global variables in header files. You must define them in one of the .c files and then use them externin the header files:

In one of the .c files:

int cond;

In one of the .h files that should be included by all .c files that need a variable:

extern int cond;
+7
source

All Articles