Header File

Header file are .h file. Only declare signature of the function so that other files can refer to.

For example the my_strlib.h could be looking like this:

extern char *my_strchr(const char *s, int c);
extern char *my_strcat(char *s1, char *s2);
extern int my_strlen(const char *str);

Which we requires my_strlib.c to have the above declaration

Example

Consider this libs/my_strlib.c

#include <stdio.h>
#include <stdlib.h>

int my_strlen(const char *str);
char *my_strcat(char *s1, char *s2);
char *my_strchr(char *s, int c);

int my_strlen(const char *str) {
  int i = 0;

  while (*(str + i)) {
    i++;
  }

  return i;
}

char *my_strcat(char *s1, char *s2) {
  char *newString = (char *) malloc((sizeof(my_strlen(s1)) + sizeof(my_strlen(s2))) * sizeof(char));
  /*char newString[100];*/ // Cannot use this since this means we declare an array using a stack. After returning out
                           // of the function, this is not kept anymore.
  char *ptr = newString;

  while (*s1) {
    *ptr++ = *s1++;
  }

  while (*s2) {
    *ptr++ = *s2++;
  }

  *ptr = '\0';
  return newString;
}

char *my_strchr(char *s, int c) {
  while (*s && *s != c) {
    s++;
  }

  if (*s != c) {
    return NULL;
  }

  return s;
}

Now libs/my_strlib.h can have the declaration of these functions

extern char *my_strchr(const char *s, int c);
extern char *my_strcat(char *s1, char *s2);
extern int my_strlen(const char *str);

In application_strlib.c we can use our library as following

#include <stdio.h>

#include "libs/my_strlib.h"

int main() {
  printf("%d\n", my_strlen("hello world"));
  printf("%s\n", my_strcat("hello", " world 123"));
  printf("%s\n", my_strchr("hello world", 'o'));
  return 0;
}

Note: See Include

Now we can compile our program as following using:

  1. Compile the object files for our libs:
    • gcc -c libs/my_strlib.c -o build/my_strlib.o
  2. Compile the program and with Object file
    • gcc build/my_strlib.o application_strlib.c -o application_strlib

And now you should have application_strlib to run.