一、实现需求
假设有一个字典,中间存储了若干字符串,类似如下
{
'函数名':{
'类型':'变量',
'类型':['变量','变量']
},
'函数名':{
'类型':'变量',
'类型':'变量'
}
}
现需根据字典中出现的字符串来查找哪些.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()