Brief about C Headers and Linking

Brief about C Headers and Linking

Headers define the prototypes of the functions , datatypes , Macros and Includes guards = ( To prevent multiple inclusions of the same header file).

// myheader.h

#ifndef MYHEADER_H  // Include guard

#define MYHEADER_H

// Function prototypes

void myFunction(int x);

int add(int a, int b);

// Macros

#define PI 3.14

// Data types

typedef struct {
    int x;
    int y;
} Point;

#endif  // MYHEADER_H
  • Include in main

And define in other file -

#include <stdio.h>
#include "myheader.h"  // Including the custom header file

void printMessage() {
    printf("Hello from my function!\n");
}

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

Complilation process

  • Includes the content of header files i.e. definitions

  • Complies main.c to .o or .obj file with the unresolved reference to those functions

  • Complies the myfunctions.c to .o … and Linker Resolves the ref.

Q. What is there are 2 definitions ?

Ans. - compile time will give the error , Linker error -

multiple definition of printMessage

Sol. -

  • Use different names for functions.

  • Use conditional compilation:

    • Use preprocessor directives like #ifdef, #ifndef, etc., to select which version of the function to compile.
// myfunctions.c

#ifdef USE_FIRST_VERSION

void printMessage() {
    printf("First version\n");
}

#else

void printMessage() {
    printf("Second version\n");
}

#endif

Note: You can define USE_FIRST_VERSION using a compiler flag (e.g., -DUSE_FIRST_VERSION).

Q. What if there is no definition?

Ans. - compile time will give the error , Linker error

undefined reference to 'printMessage'

undefined reference to 'sum'