Search code examples
cobject-files

How to use a function from an object file


I wrote a function (in "function.h" and "function.c" files), and compiled it to "function.o" file. I want to use the function defined in "function.c" in my main source, but without including "function.h". Is that possible, to compile main.c using just "function.o"?


Solution

  • A header file is (usually) just a list of declarations which are inserted textually (by #include) into your source files.

    Therefore, if function.h contains

    void foo(int x);
    

    and you have #include "function.h" in your main source file, it is exactly equivalent to just writing void foo(int x); in your source file.

    Header files are useful for code organization because it would be highly inefficient (and error-prone) to copy those declarations by hand into every source file that used them. But, if you want to avoid the header file for any reason, copying those declarations directly into your source file has the same effect as #include'ing the file.