C 语言中多个文件使用全局变量的示例(运行Python生成各个文件)

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)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值