从 python 脚本调用 gcc 给我'未定义的符号:“_main”[重复]

问题描述 投票:0回答:3

我正在尝试用 Python 编写一个代码生成器脚本,该脚本生成一个 C 源文件,编译并运行它。但是,我在从脚本中调用 gcc 时遇到问题。

一个简单的 hello world 示例:

import subprocess  

basename = "CodeGenTest";  
execname = basename;  
srcname = basename + ".c";  

codeList = [];  
codeList.append("#include <stdio.h>");  
codeList.append("int main(int argc, char *argv[])\n{");  
codeList.append("printf(\"Hello world.\\n\");");  
codeList.append("}");  

# Convert codelist to string.  
codeList.append("");  
codeString = "\n".join(codeList);  

# Print code to output source file  
outfile=open(srcname,'w');  
outfile.write(codeString);  
outfile.close;  

print "Compile.";  
cmd = ["gcc", "-O2", srcname, "-o", execname];  
p = subprocess.Popen(cmd);  
p.wait();  

subprocess.call(["./"+execname]);  

如果我运行此脚本,我会收到以下错误输出

Compile.
Undefined symbols:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

如果我在 python 解释器 shell 中执行完全相同的操作,则效果很好。我也可以直接在shell中编译代码没有问题。

我尝试了各种变体,使用 subprocess.Popen()、subprocess.call(),有或没有我能想到的所有可能的参数组合,仍然是同样的问题。

有人知道我可能遇到什么问题吗?

python c gcc code-generation
3个回答
6
投票

改变这个

outfile.close;

对此:

outfile.close()

您实际上并没有关闭文件,因此 Python 不会刷新其缓冲区,因此源文件中的所有内容都是一个空文件。当 gcc 编译空文件时,它会抱怨没有

main
函数作为程序的入口点。

我还建议您检查

p.returncode
是否为 0,以确保 gcc 在尝试执行(可能不存在)输出二进制文件之前成功。

也不需要以分号结束每个语句。如果每行有多个语句,则只需要一个分号,在这种情况下,您需要在语句之间使用它们。当前面没有反斜杠时,行尾服务器作为语句终止符。


1
投票

您实际上并不是在打电话

outfile.close
;应该是
outfile.close()
。很有可能源代码仍然卡在某个缓冲区中,而 GCC 没有看到它。


1
投票

您可以通过使用 with-block 来管理文件来避免该问题:

with file(srcname, 'w') as outfile:
    outfile.write(codeString)

另请注意,Python 中不需要分号,除非您在同一行上编写多个语句。

© www.soinside.com 2019 - 2024. All rights reserved.