import os
# 头文件 global.h 的内容
global_h_content = """
#ifndef GLOBAL_H
#define GLOBAL_H
extern int globalVar;
#endif
"""
# 源文件 file1.c 的内容
file1_c_content = """
#include <stdio.h>
#include "global.h"
int globalVar = 10; // 定义并初始化全局变量
void functionInFile1() {
printf("Value of globalVar in file1: %d\n", globalVar);
}
"""
# 源文件 file2.c 的内容
file2_c_content = """
#include <stdio.h>
#include "global.h"
void functionInFile2() {
printf("Value of globalVar in file2: %d\n", globalVar);
}
"""
# 主函数所在的源文件 main.c 的内容
main_c_content = """
#include <stdio.h>
#include "global.h"
int main() {
functionInFile1();
functionInFile2();
return 0;
}
"""
# 创建文件夹来存放文件,如果文件夹已存在则不会报错
folder_name = "c_files"
os.makedirs(folder_name, exist_ok=True)
# 写入头文件 global.h
with open(os.path.join(folder_name, "global.h"), "w") as file:
file.write(global_h_content)
# 写入源文件 file1.c
with open(os.path.join(folder_name, "file1.c"), "w") as file:
file.write(file1_c_content)
# 写入源文件 file2.c
with open(os.path.join(folder_name, "file2.c"), "w") as file:
file.write(file2_c_content)
# 写入主函数所在的源文件 main.c
with open(os.path.join(folder_name, "main.c"), "w") as file:
file.write(main_c_content)
C 语言中多个文件使用全局变量的示例(运行Python生成各个文件)
于 2024-07-17 12:32:06 首次发布