Harsh Dave Harsh Dave - 9 months ago 131
C Question

error: unknown type name ‘FILE’

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: error: unknown type name ‘FILE’.
The code is given below

app.c:

#include<stdio.h>
#include<stdlib.h>
#include"write_hello.h"

int main(){
FILE* fp;
fp = fopen("new_file.txt","w");

write_hello(fp);

return 0;
}


write_hello.h:

void write_hello(FILE*);


write_hello.c:

void write_hello(FILE* fp){
fprintf(fp,"hello");
printf("Done\n");
}


when compiling by gcc the following occurs:

harsh@harsh-Inspiron-3558:~/c/bank_management/include/test$ sudo gcc app.c
write_hello.c -o app
write_hello.c:3:18: error: unknown type name ‘FILE’
void write_hello(FILE* fp){
^


Sorry for any mistakes.I am a beginner.

Answer Source

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 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).

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");
}