// main.c
struct student { int id; char name[20]; };
// fun.c
void fun(struct student s) { ... } // 編譯錯誤:student 未定義
分別編譯 gcc -c fun.c 失敗,因 struct student 定義在 main.c 中。
在 main.c 中 #include "fun.c" 會導致重複定義、編譯緩存失效、專案結構混亂,嚴禁在生產環境使用。
student.h#ifndef STUDENT_H
#define STUDENT_H
struct student {
int id;
char name[20];
};
void fun(struct student s); // 函式宣告
#endif
#include "student.h"
void fun(struct student s) { ... }
#include "student.h"
int main() {
struct student s = {1, "Tom"};
fun(s);
return 0;
}
gcc -c main.c -o main.o
gcc -c fun.c -o fun.o
gcc main.o fun.o -o main
# 或一步到位
gcc main.c fun.c -o main
CC = gcc
CFLAGS = -Wall -g
OBJS = main.o fun.o
TARGET = main
$(TARGET): $(OBJS)
$(CC) $(OBJS) -o $(TARGET)
%.o: %.c student.h
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJS) $(TARGET)
#ifndef 護衛或 #pragma once