Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC throws error upon compilation: error: unknown type name ‘FILE’

Tags:

c

gcc

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) {
like image 732
Harsh Dave Avatar asked Mar 12 '17 05:03

Harsh Dave


1 Answers

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.

like image 54
ScottK Avatar answered Sep 22 '22 22:09

ScottK