[Linux][C]How to add user defined include directory during compilation


User defined  include directories can be added during compilation .

eg:

Write a simple c program

#include <hello.h>

int main(void)
{
printf(“Hello world \n”);
return 0;
}

Save the program as hello.c

Now create a directory named  include  in your working directory . Create an  hello.h inside include directory .

The content of hello.h is

#ifndef __HELLO_HH__

#include <stdio.h>

#endif

save the file as hello.h in the include directory

If you compile hello.c using gcc “gcc hello.c “, you will get the following error

hello.c:1:19: error: hello.h: No such file or directory
hello.c: In function main:
hello.c:4: warning: incompatible implicit declaration of built-in function printf

Reason – Compiler will check for hello.h in the system’s include directory . To fix this error , we need to inform the gcc compiler the path to search for hello.h. This can be done by adding -I followed by path  where headers are kept . 

Now compile the same using the following command “gcc hello.c -I include

This command will create an executable named a.out . a.out will print hello world on execution.

Published by RNP

A person who likes learning new languages.

Leave a comment