I am making a function which is just writes \"hello\" to a file. I have put it in a different file and included its header in the program.But gcc is giving an error namely:
FILE is defined in stdio.h and you need to include it in each file that uses it. So write_hello.h and write_hello.c should both include it, and write_hello.c should also include write_hello.h (since it implements the function defined in write_hello.h).
Also note that it is standard practice for every header file is to define a macro of the same name (IN CAPS), and enclose the entire header between #ifndef, #endif. In C, this prevents a header from getting #included twice. This is known as the "internal include guard" (with thanks to Story Teller for pointing that out). All system headers such as stdio.h include an internal include guard. All user defined headers should also include an internal include guard as shown in the example below.
write_hello.h
#ifndef WRITE_HELLO_H
#define WRITE_HELLO_H
#include <stdio.h>
void write_hello(FILE*);
#endif
write_hello.c
#include <stdio.h>
#include "write_hello.h"
void write_hello(FILE* fp){
fprintf(fp,"hello");
printf("Done\n");
}
Note that when you include system files, the header name is placed within <>
's. This helps the compiler identify that these headers are system headers which are stored in a central place based on your development environment.
Your own custom headers are placed in quotes ""
are typically found in your current directory, but may be placed elsewhere by including the path, or adding the directory to your list of directories that the compiler searches. This is configurable within your project if you are using an IDE like NetBeans, or using the -I compiler option is building it directly or through a makefile.