Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include c file in another

Tags:

c

I want to include a .c file in another. Is it possible right? It works well if I include a header file in a .c file, but doesn't work as well if I include a .c file in another .c file.
I am using Visual Studio and I get the following error:

main.obj : error LNK2005: _sayHello already defined in sayHello.obj  
/* main.c  */
#include "sayHello.c"

int main()
{
    return 0;
}  
/* sayHello.c */

#include <stdio.h>

void sayHello()
{
    printf("Hello World");
}

I don't know what this error could mean. Time to ask more advanced C coders. :)

like image 656
Andrew Avatar asked May 04 '12 11:05

Andrew


People also ask

Can we include .C file in another .C file?

You can include a . c file inside another; this is rarely done because it can be confusing.

Do you include C file in header file?

One simple rule, never include C files into other C files, and never include anything into H files. If you are trying to use code written by someone else, then usually there will be a C file and an H file with matching names.

How do you use a function from a different file C?

You must declare int add(int a, int b); (note to the semicolon) in a header file and include the file into both files. Including it into Main. c will tell compiler how the function should be called.


1 Answers

I want to include a .c file in another.

No you don't. You really, really don't. Don't take any steps down this path; it only ends in pain and misery. This is bad practice even for trivial programs such as your example, much less for programs of any real complexity. A trivial, one-line change in one file will require you to rebuild both that file and anything that includes it, which is a waste of time. You lose the ability to control access to data and functions; everything in the included .c file is visible to the including file, even functions and file scope variables declared static. If you wind up including a .c file that includes another .c file that includes another .c file und so weiter, you could possibly wind up with a translation unit too large for the compiler to handle.

Separate compilation and linking is an unequivocal Good Thing. The only files you should include in your .c files are header files that describe an interface (type definitions, function prototype declarations, macro defintions, external declarations), not an implementation.

like image 121
John Bode Avatar answered Oct 06 '22 00:10

John Bode