I am having problem of multiple declaration during compilation of multiple dependent c files.
I had been including the source files in main.c and compile it. It worked fine. Lately I was advised by my colleague not to do in that way. So I tried to change my code and compile it making different .o files and finally linking them. But it did not work.
Basically what I am trying to do is similar to this:
essentials.h
#ifndef ESSENTIALS
#define ESSENTIALS
//C headers
#include <stdio.h>
#include <conio.h>
//My Assets
#include <new.h>
#include <global.h>
#endif
This header includes all the basic files any source file may need. Also it includes header file where the global variables are declared.
The other header and source files are such as:
global.h
#ifndef GLOBAL
#define GLOBAL
int glob_int=0;
#endif
new.h
#ifndef NEW
#define NEW
int thisFunc();
#endif
new.c
#include <essentials.h>
int thisFunc(){
glob_int++;
printf("This is new Function %d\n",glob_int);
return 0;
}
main.c
#include <essentials.h>
/* include other headers*/
int main(){
printf("Main Function Start %d\n",glob_int);
thisFunc();
return 0;
}
I then proceed to compile the following,
F:\Codes\prog> gcc -c ./src/*.c -I"F:\Codes\prog\include"
<<<< Compiles separate obj files >>>>
F:\Codes\prog> gcc *.o -o ./bin/main.exe
c:/my_assets/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-
mingw32/bin/ld.exe:
new.o:new.c:(.bss+0x0): multiple definition of `glob_int'; main.o:main.c:(.bss+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
I have to use glob_int in both the source files. What am I missing about the linking phase?And are there any suitable ways to compile this code.
I have searched various such examples but nothing has worked for my case. The thing is without the glob_int variable, the program compiles and runs too without showing any multiple declaration error for the thisFunc() function. But it does not compile with the variable.
I also have tried putting <global.h> in each .c files instead of in essentials header file. But that too didn't work.
Please avoid giving me hints for using extern. That will be the last thing I would use.
ALSO: Please I would like to know why including source files in main.c with guard headers and compiling it is usually condemned by many C programmers. If you instead can describe about this please help by answering.
Thanks Sammy1410