Skip to content

Instantly share code, notes, and snippets.

@fabrizzio-gz
Last active January 30, 2021 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabrizzio-gz/d2e880615be13489ec3c18d3cae21648 to your computer and use it in GitHub Desktop.
Save fabrizzio-gz/d2e880615be13489ec3c18d3cae21648 to your computer and use it in GitHub Desktop.
Dividing a C program into multiple files demonstration.
#include <stdio.h>
/* Extra files headers */
#include "types.h"
#include "special_functions.h"
void helper_function();
/* Main program */
int main() {
struct struct_type my_struct = { .val1 = 1 , .val2 = 1};
union union_type my_union = { .n = 1 };
special_function(my_struct, my_union);
helper_function();
printf("Success!\n");
return 0;
}
void helper_function() {
printf("helper function: I'm called from main!\n");
}
#include <stdio.h>
/* Type definitions */
typedef int my_type;
struct struct_type {
my_type val1;
int val2;
};
union union_type {
my_type n;
char c;
};
/* Extra function prototypes */
void special_function(struct struct_type my_struct, union union_type my_union);
void helper_function();
/* Main program */
int main() {
struct struct_type my_struct = { .val1 = 1 , .val2 = 1};
union union_type my_union = { .n = 1 };
special_function(my_struct, my_union);
printf("Success!\n");
return 0;
}
/* Extra function definitions */
void special_function(struct struct_type my_struct, union union_type my_union) {
helper_function();
}
void helper_function() {
printf("helper function: I'm called by special_function!\n");
}
all: main.c special_functions.c types.h
gcc main.c special_functions.c -o main

Dividing a C program into multiple files

Example initial file: main_single_file.c.

Divided into several files:

  • main.c
  • types.h
  • special_functions.c
  • special_functions.h

Tutorial instructions here.

#include <stdio.h>
#include "types.h"
static void helper_function();
/* Extra function definitions */
void special_function(struct struct_type my_struct, union union_type my_union) {
helper_function();
}
static void helper_function() {
printf("helper function: I'm called by special_function!\n");
}
#ifndef SPECIAL_FUNCTIONS_H
#define SPECIAL_FUNCTIONS_H
/* Extra function prototypes */
void special_function(struct struct_type my_struct, union union_type my_union);
#endif
#ifndef TYPES_H
#define TYPES_H
/* Type definitions */
typedef int my_type;
struct struct_type {
my_type val1;
int val2;
};
union union_type {
my_type n;
char c;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment