Reputation: 1180
I have a C program named coderTest.c in a directory. In a sub-directory, src, I have several files, one.c, two.c, three.c, and their associated header files one.h, two.h, three.h.
I want to use functions from one.c and two.c in coderTest.c. Both one.c and two.c use functions from three.c. Do I need to include three.c in coderTest.c, or will it take care of it's dependency on it's own?
I am using #include "src/one.h"
for one and two.
Upvotes: 1
Views: 179
Reputation: 23218
You can do what you want several ways as long as visibility to necessary prototypes is provided. In addition to where best to include header files, consider using wrappers to guarantee your header is used only once:
#ifndef _SOMEFILE_H_
#define _SOMEFILE_H_
the entire file
#endif /* SOMEFILE_H__SEEN */
Also consider readability. For example given: coderTest.c, one.c/.h, two.c/.h, three.c/.h are as you described:
1) You should include three.h in both one.c and two.c.
2) For coderTest.c, #include headers of all supporting headers either in the file itself, or perhaps in a collector header: conderTest.h:
coderTest.h:
#include "./src/one.h"
#include "./src/two.h"
#include "./src/three.h"
coderTest.c
#include "coderTest.h"
Upvotes: 0
Reputation: 37914
Do I need to include three.c in coderTest.c, or will it take care of it's dependency on it's own?
You don't need to include "src/three.h"
in coderTest.c
, but this does not mean, that compiler does handle dependency automagically. This header needs to be included in one.c
, two.c
and three.c
. The last one is to confirm that header's declarations and definitions match with each other properly.
As a result, you project might look as:
coderTest.c
:#include "src/one.h"
#include "src/two.h"
// ...
src/one.c
:#include "one.h"
#include "three.h"
// ...
src/two.c
:#include "two.h"
#include "three.h"
// ...
src/three.c
:#include "three.h"
// ...
To prevent multiple includes of same header, use header guards for each header file individually.
Upvotes: 2
Reputation: 542
As long as two.c
and one.c
properly #include "three.h"
then the compiler will be able to chain the dependencies together without a problem. If you wanted to run something from three.c
in coderTest.c
it would want you to #include it in there as well.
Do your files have the preprocessor directives #IFNDEF
, #DEFINE
, and #ENDIF
in place to prevent duplicate importing?
Upvotes: 0
Reputation: 1048
In coderTest.c, include the following:
#include "src/two.h
#include "src/one.h
In one.c, include:
#include "src/three.h
In two.c, include:
#include "src/three.h
Do I need to include three.c in coderTest.c, or will it take care of it's dependency on it's own?
No you don't need to include three.c in coderTest.c, because one.c and two.c abstract it away.
Upvotes: 0