Can't we include .c file?

c, c++, include

Solution

Do it as follows:

`abc.c`:

#include <stdio.h>
void abc()
{printf("From ABC() \n");}

`main.c`:

#include<stdio.h>
#include "abc.c"
int main()
{   
    abc();
    return 0;
}

(no need for the header file)

Then, to compile, you'd only compile `main.c`. Do not attempt to compile both `abc.c` and `main.c`, because then you'd have the `abc()` function defined twice.

You need to understand that `#include` is basically "copy-paste", nothing more. If you tell it `#include "abc.c"`, it will simply take the contents of `abc.c`, and "paste" them in your `main.c` file. Therefore, using the above for `main.c`, after the preprocessor processes it, your `main.c` will look like this (I'm ignoring the `#include <stdio.h>`s):

#include<stdio.h>
#include <stdio.h>
void abc()
{printf("From ABC() \n");}
int main()
{   
    abc();
    return 0;
}

which is a valid program.

That said you should generally not do this; you should compile all your `.c` files separately and only then link them together.

Problem

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.

Original source