ratzip
ratzip

Reputation: 1671

include header files in C

I am a newbie to C and C++ language, I have a question about header files in C:

a.h

#define HELLO (1)
typedef struct
{
   int a;
   int b;
} hello;

b.h

#include "a.h"
#define NUMBER (3)

main.c

#include "b.h"

in main.c, does struct and macro defined in a.h can be used in main.c?

Upvotes: 0

Views: 171

Answers (4)

Ayman Younis
Ayman Younis

Reputation: 156

Sure you can use both Struct and MACROS in the main.c

You need to be aware of the C Compilation Process, Before main.c is being compiled or linked, there is the pre-processor step:

Preprocessor:

  • The input to this phase is the .c File and .h Files
  • The preprocess process the preprocessor keywords like #define, #ifdef, #include, etc. and generate a new .pre file or .i file after the text replacement process.
  • The output of this phase is a C Code without any preprocessor keyword.

enter image description here

So the main.c will actually look like this:

#define HELLO (1)
typedef struct
{
   int a;
   int b;
} hello;
#define NUMBER (3)

And then replace all macros, here you don't use HELLO or NUMBER, so the pure c main file will be:

typedef struct
{
   int a;
   int b;
} hello;

Upvotes: 1

capac
capac

Reputation: 11

Yep, #include statements can chain multiple files together. #include literally copies and pastes the contents of one file into another, so you can think of it as a one-after-another effect.

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 181199

Yes, #include directives themselves appearing in included files have their normal effect, up to an implementation-defined limit on the number of levels of inclusion. The "normal effect" is equivalent to textual interpolation -- that is, there is no separate scoping for the contents of included files -- so any declaration appearing in any directly or indirectly included file is visible to all code following the point of inclusion.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

Yes, it can be used. That is the sole purpose of #includeing of header files.

For more information, you can see the preprocessed version of code. Use

gcc -E <filename.c>  //main.c, in this case

There you can see the presence of the struct and MACROS definde in the included header files.

Upvotes: 0

Related Questions