If we have a number of C sources and header files then how to create an executable from all these. This post is a template for that concept. This post contains a Makefile which is a simple but standard makefile which can be used as a template. I thought of writting this when I started working on embedded programs with C.This post not explains shared library concept.
Take the simplest case, a single main.c file.
#include <stdio.h>
int main ( void )
{
printf("This is a test\n");
return 0;
}
compile it: $gcc -o main main.c
$./main will print the result.
Consider another situation where we have functions defined in different files/directories. Then how to compile to create an executable. Here comes -c, -o options and object file concepts.
I am not writting any explenation for this. Create the following files in a directory and experiment.
Consider we have three functions and a header file another.c define.h functions.c main.c
Take the simplest case, a single main.c file.
#include <stdio.h>
int main ( void )
{
printf("This is a test\n");
return 0;
}
compile it: $gcc -o main main.c
$./main will print the result.
Consider another situation where we have functions defined in different files/directories. Then how to compile to create an executable. Here comes -c, -o options and object file concepts.
I am not writting any explenation for this. Create the following files in a directory and experiment.
Consider we have three functions and a header file another.c define.h functions.c main.c
main.c
--------
#include <stdio.h>
int main ( void )
{
printf ( "%s\n", "This is a printf from main function" );
function_one();
return 0;
}
functions.c
--------------
#include <stdio.h>
#include <define.h>
void function_one ( void )
{
printf("function_one has been executed. The defnition is: %d\n", NUMBER );
another_fun();
}
void function_two ( void )
{
printf("function_two has been executed.\n");
}
another.c
-----------
#include <stdio.h>
void another_fun ( void )
{
printf ( "Another function\n" );
}
define.h
-----------
#define NUMBER 142
Makefile
-----------
CC := gcc
OBJECTS := functions.o main.o another.o
INC1 := ./
INCLUDES := -I$(INC1)
bin: $(OBJECTS)
$(CC) $(OBJECTS) -o bin
functions.o: functions.c
$(CC) $(INCLUDES) -c functions.c -o functions.o
main.o: main.c
$(CC) -c main.c -o main.o
another.o: another.c
$(CC) -c another.c -o another.o
clean:
rm -rf bin *.o