前置知识: C

多文件编译

1 minIntermediate2026/6/14

多文件项目与头文件组织

1. 头文件

// utils.h
#ifndef UTILS_H
#define UTILS_H

int add(int a, int b);
void print_hello(void);

#endif
// utils.c
#include "utils.h"
#include <stdio.h>

int add(int a, int b) { return a + b; }
void print_hello(void) { printf("Hello!\n"); }

2. 编译

gcc -c utils.c -o utils.o
gcc -c main.c -o main.o
gcc utils.o main.o -o program

3. Makefile

CC = gcc
CFLAGS = -Wall -Wextra -std=c17

SRCS = main.c utils.c
OBJS = $(SRCS:.c=.o)
TARGET = program

$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

clean:
	rm -f $(OBJS) $(TARGET)