Search code examples
c++cfunctionheaderusing

C: Using functions from files within in the same project


My question does not link to a direct example, but is more of a question as a whole. When I was coding with C++, I found (after looking through some threads) that in order to use functions from different files that are in the same project, I would either need a header file. So, for example, if I have the main function in a file called "main.cpp" and I wanted to use a function, "prob1()" in another file called "problem1.cpp", I would need to use a header file.

What is confusing me is why I do not have to worry about this for programming in C? When I was programming in C, in order to use functions from different files, I could call the function directly.

Any help/explanation is appreciated. Thanks!


Solution

  • Your C compiler can implicitly declare the function, but you should be doing so yourself. If you turn up the warnings, you'll see something like:

    file1.c: warning: implicit declaration of function ‘func_from_f2’
    

    When file1.c is being compiled, this implicit declaration will be used to create an object file and then when linking you have to just hope that the function actually does exist and the declaration is correct so that the object files can be linked together successfully.

    If not, the linker will give you an error somewhere along the lines of:

    undefined reference to `func_from_f2'
    


    You also don't necessarily need a header file, you can simply include the declaration/prototype of the function in your source file (the #include directive essentially does this for you). ie. the below will work fine without warnings:

    file1.c

    void func_from_f2(void);
    
    int main(void)
    {
       func_from_f2();
    
       return 0;
    }
    

    file2.c

    #include <stdio.h>
    
    void func_from_f2(void)
    {
       puts("hello");
    }
    


    However, it's usually best practice that you do use a header file:

    file1.c

    #include "file2.h"
    
    int main(void)
    {
       func_from_f2();
    
       return 0;
    }
    

    file2.h

    #ifndef FILE2_H
    #define FILE2_H
    
    void func_from_f2(void);
    
    #endif
    

    file2.c

    #include <stdio.h>
    #include "file2.h"
    
    void func_from_f2(void)
    {
       puts("hello");
    }