This content originally appeared on DEV Community and was authored by As Manjaka Josvah
Voici un exemple simple d’un projet en C avec un Makefile, un fichier d’en-tête (.h), et deux fichiers source (utils.c et main.c).
  
  
  1. Fichier d’en-tête : utils.h
#ifndef UTILS_H
#define UTILS_H
// Fonction pour additionner deux entiers
int addition(int a, int b);
#endif // UTILS_H
  
  
  2. Fichier source : utils.c
#include "utils.h"
// Implémentation de la fonction d'addition
int addition(int a, int b) {
    return a + b;
}
  
  
  3. Fichier principal : main.c
#include <stdio.h>
#include "utils.h"
int main() {
    int a = 5;
    int b = 3;
    int result = addition(a, b);
    printf("La somme de %d et %d est : %d\n", a, b, result);
    return 0;
}
  
  
  4. Makefile : Makefile
# Variables
CC = gcc
CFLAGS = -Wall -g
SOURCES = main.c utils.c
OBJECTS = $(SOURCES:.c=.o)
TARGET = mon_programme
# Règle par défaut
all: $(TARGET)
# Lien de l'exécutable
$(TARGET): $(OBJECTS)
    $(CC) -o $@ $^
# Compilation des fichiers .c en .o
%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@
# Nettoyage des fichiers objets
.PHONY: clean
clean:
    rm -f $(OBJECTS)
# Nettoyage complet (fichiers objets et exécutable)
.PHONY: fclean
fclean: clean
    rm -f $(TARGET)
# Refaire la compilation
.PHONY: re
re: fclean all
Structure du projet
Voici comment devrait être organisée la structure des fichiers :
/mon_projet
├── Makefile
├── main.c
├── utils.c
└── utils.h
Utilisation
- Pour compiler le programme, exécute dans le terminal :
make
- Pour nettoyer les fichiers objets :
make clean
- Pour nettoyer complètement :
make fclean
- Pour reconstruire le programme :
make re
Résultat attendu
Après avoir exécuté make, tu obtiendras un exécutable nommé mon_programme. En exécutant ce programme, il affichera :
La somme de 5 et 3 est : 8
This content originally appeared on DEV Community and was authored by As Manjaka Josvah
