【发布时间】:2011-05-16 15:37:03
【问题描述】:
我正在尝试用 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(),有或没有我能想到的所有可能的参数组合,仍然是同样的问题。
有人知道我的问题是什么吗?
【问题讨论】:
-
这听起来像是一个非常糟糕的想法的精简示例。如果不使用(非字符串!)内部表示(AST = abstract 语法 tree),您将无法编写编译器,同样您也无法仅使用字符串。
-
代码生成器将生成、编译和运行一段非常具体的代码,并针对各种优化参数(即自动调谐器)对其进行评估,并最终生成最佳版本代码,运行时。我非常清楚需要对代码进行更高级别的抽象,但有时我需要生成和编译代码,这篇文章就是一个简单的例子。
标签: python c gcc code-generation