Search code examples
cc-header

How to write a C header file properly so that a function declared by that header file can be linked without any error?


I am trying to write a C header file in this manner:

// header.h
#ifndef HEADER_H
#define HEADER_H

extern int add(int a, int b);

#endif
// header.c
#include "header.h"

int add(int a, int b)
{
    return (a+b);
}

Now suppose I have a main.c file like this:

// main.c
#include <stdio.h>
#include "header.h"

int main(void)
{
    print("%d", add(2,3));
    return 0;
}

I get an error when compiling main.c and GCC says " undefined reference to 'add' ". Can you please explain where have I gone wrong?

EDIT:
I think I didn't make myself very clear previously. What I am actually trying to say is that, I've seen that most C programmers follow the above mentioned style of writing the header files, and I've also heard that this reduces the size of the final binary that's generated. I'm trying to do something similar but I get an error every time I try to compile my code. I added that extern keyword so that the compiler understands that the function is defined somewhere externally, but it still failed to compile.

How can I compile the above code successfully with the implementation of the said programming style?


Solution

  • There are two problems:

    header.h

    // header.h
    #ifndef HEADER_H
    #define HEADER_H
    
    int add(int a, int b);
    
    #endif
    
    • You don't need "extern"
    • You shouldn't have the trailing "/"
    • You should have a newline after the final "#endif"

    Example gcc command:

    gcc -g -Wall -pedantic main.c header.c -o myprog
    

    You need to compile both "main.c" and "header.c", and include both ".o" files in your build.

    It sounds like the "undefined reference" was a linker error: you probably failed to include "header.o".