C语言作为一门结构化编程语言,有多种常见的代码架构模式。以下是几种主要的架构方式:
1. 单文件架构
最简单的架构,适用于小型项目或学习用途:
// main.c
#include <stdio.h>
// 函数声明
void function1();
int function2(int param);
// 全局变量(谨慎使用)
int global_var;
int main() {
// 程序入口
function1();
return 0;
}
// 函数定义
void function1() {
printf("Function 1\n");
}
int function2(int param) {
return param * 2;
}
```
2. 多文件模块化架构
2.1 更常见的专业项目架构,将代码按功能拆分:
project/
├── main.c // 程序入口
├── module1.h // 模块1头文件
├── module1.c // 模块1实现
├── module2.h // 模块2头文件
└── module2.c // 模块2实现
2.2 示例头文件(module1.h):
#ifndef MODULE1_H
#define MODULE1_H
// 只包含必要的头文件
#include <stdint.h>
// 常量定义
#define MAX_SIZE 100
// 类型定义
typedef struct {
int id;
char name[50];
} User;
// 函数声明
void module1_init();
int module1_process_data(const char* input);
#endif
```
3. 分层架构
将系统分为不同的逻辑层次:
```
project/
├── application/ // 应用层
├── business/ // 业务逻辑层
├── data/ // 数据访问层
└── utils/ // 工具函数
```
4. 基于组件的架构
将系统划分为独立的组件,每个组件有明确的接口:
```
project/
├── components/
│ ├── logger/ // 日志组件
│ ├── network/ // 网络组件
│ └── database/ // 数据库组件
└── main.c
```
5. 面向对象风格架构
虽然C不是面向对象语言,但可以模拟OOP:
// shape.h
typedef struct {
void (*draw)(void* self);
void (*move)(void* self, int x, int y);
} Shape;
// circle.h
#include "shape.h"
typedef struct {
Shape base;
int x, y;
int radius;
} Circle;
Circle* circle_create(int x, int y, int radius);
```
6. 事件驱动架构
常见于GUI或嵌入式系统:
// event_loop.c
while(1) {
Event event = get_next_event();
switch(event.type) {
case EVENT_BUTTON_PRESSED:
handle_button(event.data);
break;
case EVENT_TIMER:
handle_timer();
break;
// ...
}
}
```
7. 插件架构
支持动态加载功能模块:
// plugin.h
typedef struct {
const char* name;
void (*init)();
void (*execute)(const char* params);
} Plugin;
// main.c
void load_plugin(const char* path) {
void* handle = dlopen(path, RTLD_LAZY);
Plugin* plugin = dlsym(handle, "exported_plugin");
plugin->init();
}
最佳实践
1. 头文件保护:使用`#ifndef`防止重复包含
2. 最小依赖:头文件只包含必要的其他头文件
3. 清晰的接口:头文件是模块的接口,保持简洁
4. 避免全局变量:尽量通过函数参数传递数据
5. 一致的命名约定:如`module_do_something()`
选择哪种架构取决于项目规模、团队习惯和具体需求。小型项目可能只需要简单的多文件架构,而大型系统可能需要更复杂的分层或组件化架构。