20230505根据txt文件编译指定源文件(下)

这里写目录标题

一、实现需求

假设有一个字典,中间存储了若干字符串,类似如下

{
	'函数名':{
		'类型':'变量',
		'类型':['变量','变量']
		},
	'函数名':{
		'类型':'变量',
		'类型':'变量'
		}
}

现需根据字典中出现的字符串来查找哪些.c文件中出现过,并将这些.c文件进行编译

完整代码

#接上文

# 定义路径宏定义
SRC_DIR = "\Src"
INC_DIR = "\Include"

# 遍历当前Src目录下的所有.c文件,将其路径存储在一个列表中,例如c_files。
c_files = []
for root, dirs, files in os.walk(SRC_DIR):
    for file in files:
        if file.endswith(".c"):
            c_files.append(os.path.join(root, file))

# 遍历Include目录下的所有.h文件,将其路径存储在一个列表中,例如h_files。
h_files = []
for root, dirs, files in os.walk(INC_DIR):
    for file in files:
        if file.endswith(".h"):
            h_files.append(os.path.join(root, file))

# 找到所有包含这些函数名或.h文件名的.c文件,将其路径存储在一个列表中,例如match_files。
match_files = []
for func in search_values:
    # 对函数名称中的特殊字符进行转义
    # func = re.escape(func)
    # 使用grep查找包含函数名的.c文件
    grep_cmd = "grep -l {0} {1}".format(func, ' '.join(c_files))
    result = subprocess.Popen(grep_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    match_files.extend(filter(None,result[0].strip().split("\n")))
# 使用grep查找包括头文件在内的.c文件
for header in h_files:
    grep_cmd = "grep -l {0} {1}".format(header, ' '.join(c_files))
    result = subprocess.Popen(grep_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    match_files.extend(filter(None,result[0].strip().split("\n")))

# 去除重复的文件路径
match_files = list(set(match_files))

# 将匹配的.c文件编译成.o文件。
obj_files = []
for file in match_files:
    obj_file = file.replace(".c", ".o")
    gcc_cmd = "gcc -c {0} -l{1} -o {2}".format(file, INC_DIR, obj_file)
    subprocess.Popen(gcc_cmd, shell=True).wait()
    obj_files.append(obj_file)

# 将所有.o文件打包成一个.a文件。
ar_cmd = "ar -rcs libmylib.a {0}".format(' '.join(obj_files))
subprocess.Popen(ar_cmd, shell=True).wait()
sys.exit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值