Today I had an interview there they asked me can we include .c file to a source file?
I said yes. Because few years back I saw the same in some project where they have include .c file. But just now I was trying the same.
abc.c
#include<stdio.h>
void abc()
{ printf("From ABC() \n"); }
main.c
#include<stdio.h>
#include "abc.c"
int main()
{ void abc();
return 0;
}
Getting an error:
D:\Embedded\...\abc.c :- multiple definition of 'abc'
Where is it going wrong?
I wrote an abc.h file (the body of abc.h is { extern void abc(void); }),
and included the file in abc.c (commenting out #include abc.c). Worked fine.
Do it as follows:
abc.c:main.c:(no need for the header file)
Then, to compile, you’d only compile
main.c. Do not attempt to compile bothabc.candmain.c, because then you’d have theabc()function defined twice.You need to understand that
#includeis basically “copy-paste”, nothing more. If you tell it#include "abc.c", it will simply take the contents ofabc.c, and “paste” them in yourmain.cfile. Therefore, using the above formain.c, after the preprocessor processes it, yourmain.cwill look like this (I’m ignoring the#include <stdio.h>s):which is a valid program.
That said you should generally not do this; you should compile all your
.cfiles separately and only then link them together.