Boba
Boba

Reputation: 91

using user defined header file C

I'm confused about how to create a user defined header files and how to use it, so I'd like to ask if I get it correct.

If I have two C programs, one is demo.c and one is called tree.c, and I can create a header file tree.h:

#ifndef TREE_H
#define TREE_H

//some prototypes here
int size();
int isFull();

#endif

and in the actual tree.c program I put all the actual functions,

#include "tree.h"

int size()
{
//some implementation
}

int isFull()
{
//some implementation
}

I'm wondering if I have another program called demo.c, can I just include the tree.h header and use the function in the tree.c? just like what we do in Java using another class? Do I need to put them in the same directory?

Upvotes: 1

Views: 1149

Answers (1)

Daniel Walker
Daniel Walker

Reputation: 6772

In short, yes, you can just do #include "tree.h" in demo.c.

If tree.h isn't in the same directory as demo.c, you can either include its path via #include "some/other/dir/tree.h" or you could pass an include flag in your compiler invocation. For example, if you're using gcc, you could do -Isome/other/dir.

demo.c only needs to see the function prototypes which tree.h contains so that it knows what kind of functions it's calling. tree.c isn't needed until you want to compile this into an executable.

Upvotes: 2

Related Questions