Search code examples
cglobal-variablesheader-files

How to use header files to include functions and variables from different files


I have a program that consists in three files 01.h, main.c, 01.c.

01.h is:

int b;
void jumbo();

01.c is:

#include "01.h"
int main()
{
    //some code
    b = 7;
    //some code
}
// some code
void jumbo()
{
//some code
}

main.c is:

#include "01.h"

int main()
{
    // some code
    printf(" %d", b);
    jumbo();
}

I am encountering two problems:

  • value of b printed is 0 in main.c instead of 7.

  • On calling jumbo() in main.c the compiler shows following error:

  • main.c:|| undefined reference to `jumbo'|
  • ||error: ld returned 1 exit status|

What am I doing wrong and how can I use header files to include functions and variables from different files?


Solution

  • The undefined reference to jumbo is more than likely because you don't include 01.c in your compilation.

    When you include the header 01.h you are only including the function prototype, you are promising the compiler that a function exists with that name, arguments, and return type. When the code is compiled the compiler will look for such implementation, if it doesn't find it, it can't compile the program because it has no knowledge of what such function should do.

    To really include the function implementation you need to compile and link the file where the function is implemented, in this case 01.c.

    Now if you do that you'll have a new error which will be something along the lines of multiple definitions of main.

    What you need to do is to remove the main implementaion from 01.c and include this file in your compilation process, it would look something like this:

    01.h:

    int b = 7; // normally you wouldn't do this, in headers is usual to define constants only
               // b is indeed a global variable and these should only 
               // be used if you absolutely have to
    void jumbo();
    

    main.c:

    #include "01.h"
    #include <stdio.h>
    
    int main()
    {
        // some code
        printf(" %d", b);
        jumbo();
    }
    

    01.c:

    // here you don't need to include 01.h
    void jumbo()
    {
        //some code
    }
    

    This is a possible compilation command with gcc:

     gcc main.c 01.c -o program_name
                ^^^^
    

    You can add some routine warning flags to detect potential problems in your code:

    gcc main.c 01.c -o program_name -Wall -Wextra -pedantic   
                                    ^^^^^^^^^^^^^^^^^^^^^^^
    

    Here you have a live sample