Search code examples
cgccheader-filesobject-files

How to add .h and .o files to gcc


I'm trying to figure out how to add header and object files to the standard library so that I can use my custom files as easy as the standard library.

Currently I have to type the path to the header file in the .c file and then link the object file path when compiling.

I would like to just be able to add:

#include <mystdlib.h>

and not worry about linking the object file like I do when I reference the stdio.h header file.

I have searched around, but I fear I'm not using the proper terminology as I don't seem to find the results I need. Am I the first to want to do this, or it is just impossible, and therefore people don't even try?


Solution

  • gcc uses environment variables C_INCLUDE_PATH and LIBRARY_PATH to look for header and library files. Setting them somewhere (eg., your bash_profile) should achieve what you describe:

    export C_INCLUDE_PATH="$HOME/include"
    export LIBRARY_PATH="$HOME/lib"
    

    Alternatively, the -I and -L flags add directories to the list of directories to be searched for header files and library files, respectively.

    edit: As noted by @ChrisStratton below, the library name or object file needs to be explicitly specified. AFAIK, there is no way to make gcc always link against a library (like with libc).

    sources:

    https://gcc.gnu.org/onlinedocs/gcc/Environment-Variables.html https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html