It's a good idea to separate your project into separate files. For example, I2C functions can be separated into i2c.c and i2c.h files, SPI functions can be separated into spi.c and spi.h files, global variables can be separated to globals.h, and #defines can be separated to defines.h files. That way your program is going to be easier to read and understand.
When you separate variables or functions to other files, your main program needs to be able to find them.
This is an example of simple program separated into two source files - main.c and functions.c.
#include <stdio.h>
#include <functions.h>
int external_variable=0;
void main()
{
int variable_1=10;
external_variable=test_function(variable_1);
}
functions.c
#include <stdio.h>
#include <functions.h>
int test_function(int var_1)
{
int var_2=var_1+5;
return var_2;
}
functions.h
extern int external_variable;
int test_function(int var_1);
We also have "extern" variable. Extern variable is used in case when you need to access a variable from multiple source files. First step is variable declaration. That is done in header file, for example in functions.h.
extern int external_variable;
Do not define the variable here (do not assign a value to it). That is done in one of the source (.c) files, for example - extern variable definition in main.c:
int external_variable=0;
Do not define a variable more than once! By including a "functions.h" file in any other file, you will gain access to that variable.
Function prototypes should be done in .h files, function definitions in .c files.
functions.c
int test_function(int var_1)
{
int var_2=var_1+5;
return var_2;
}
functions.h
int test_function(int var_1);
Always make sure that arguments of the function prototype and function definitions are the same. Sometimes you can use the functions without declaring it in header file. This is a bad idea since implicitly defined functions return integer value. Depending on your function that may work fine at the moment, but it's a very bad idea so avoid that.
Copyright 2024-2025, Mario Matovina
Send me an e-mail