You are here:

C/file inclusion in C

Advertisement


Question
Hi,

I wrote 2 files in the same project. main.c and array.c. I want to to access the functions in array.c from my main.c file. My friend told me the way to do that is to create a header file and include it in main.c. However, for my exercise I can only submit the two files main.c and array.c. So in main.c I wrote

#include "array.c"

However when I compile I got error for every single function in array.c saying the function is defined more than once but when I click the error message it only shows me the function in array.c and no where else. Thank you.

Answer
Hello Pearson

Your friend is right! The correct way is to create a header file having the declarations of all the functions which are in array.c. That header file should be included in both array.c and in any other file that uses those functions - in this case main.c. The header is included in array.c so that the compiler can check declarations in the header against the actual definitions in array.c. The header is included in main.c so that the compiler can check that the functions are being called correctly.

If you include array.c in main.c and compile array.c separately into an object file, then each function in array.c will exist twice - once in the object file array.o and once in main.o. That is why you are getting the linker errors. Of course you could include array.c into main.c and not compile array.c at all, and that would work for your case, but as soon as you tried to use the array functions in more than one file, you'd be back to the same linker problems. Including one C file in another is usually not a good idea.

You can get around this by putting the array.c function declarations into main.c. That is not a good technique from the point of view of program maintenance. However, perhaps your instructors will appreciate your idea of putting the array functions into their own file. It IS a good idea, but to do it correctly, you need a header file as well.

Just to make it clear, when I say "function declaration", I mean something like this:
void foo(int x);

when I say "function definition", I mean a function with a body, like this:
void foo(int x)
{
/* function body here */
}

It is the declarations that need to be put into a header file, or, if you are limited to just 2 files, then put the declarations into main.c.

I hope that helps.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.