meta data for this page
  •  

Using Multiple files

Files:

  • main.c - main file, contains implementations of main() and run()-functions.
main.c
#include "main.h"
 
int main(int argc, char *argv[])
{
 printf("Main\n");
 
 run(argc);
 
 return 0;
}
 
void run(int _type)
{
  if(check(_type) < 0) printf("Error\n");
  else printf("Success\n");
}
  • main.h - header for main.c, contains prototype for run()-function.
main.h
#include <stdio.h>
 
void run();
  • file.c - additional file, contains implementation of check()-function.
file.c
#include "file.h"
 
int check(int _type)
{
  if(_type == RIGHT) return 1;
  else return -1;
}
  • file.h - header for file.c, contains prototype for check()-function.
file.h
#define RIGHT 0
 
int check(int);

To use the function defined in file.h and implemented in file.c in the main.c following steps are needed:

  1. Include the file.h in main.c (or in main.h)
    • main.c after modifications:
      main_mod.c
      #include "main.h"
      #include "file.h
       
      int main(int argc, char *argv[])
      {
       printf("Main\n");
       
       run(argc);
       
       return 0;
      }
       
      void run(int _type)
      {
        if(check(_type) < 0) printf("Error\n");
        else printf("Success\n");
      }
    • After this the compiler and linker can find the function check() used in run() since it is defined in one of the headers included.
  2. Add file.c into the Makefile of the application as source (remember to separate multiple files with spaces), in this case
    SOURCES=main.c file.c

CT30A5002 - Games and Networking