Is it possible to compile c code using python?

18,266

Solution 1

Sure, why not? Of course, you'd need GCC installed (or llvm) so you have something to compile with. You can just use os.system, or any of the other ways for calling an external program.

Of course, you're probably better off looking at something like SCons, which already exists to solve this problem.

Plus, to answer the question actually asked, there's nothing that would prevent you from writing a compiler/assembler/linker in python, they're just programs like anything else. Performance probably wouldn't be very good though.

Solution 2

Step 1. Get PLY. Python Lex and Yacc. http://www.dabeaz.com/ply/

Step 2. Find a Yacc/Lex configuration for C. http://www.lysator.liu.se/c/ANSI-C-grammar-y.html

Step 3. Tweak PLY to use the C language rules you found.

Step 4. Run. You're "compiling" C code -- checking the syntax.

Solution 3

You can compile C code using only the standard library, and it will work on every platform and with every Python version (assuming you actually have a C compiler available). Check out the distutils.ccompiler module which Python uses to compile C extension modules. A simple example:

// main.c

#include <stdio.h>

int main() {
    printf("Hello world!\n");
    return(0);
}

Compilation script:

# build.py
from distutils.ccompiler import new_compiler

if __name__ == '__main__':
    compiler = new_compiler()
    compiler.compile(['main.c'])
    compiler.link_executable(['main.o'], 'main')

Everything else (include paths, library paths, custom flags or link args or macros) can be passed via various configuration options. Check out the above link to the module documentation for more info.

Solution 4

If I understood you clearly, you just want to run compiler with some arguments from python?

In this case, you can just to use os.system. http://docs.python.org/library/os.html#os.system

Or better way is module "subprocess". http://docs.python.org/library/subprocess.html#module-subprocess

Share:
18,266
RanZilber
Author by

RanZilber

Updated on June 13, 2022

Comments

  • RanZilber
    RanZilber almost 2 years

    I want to build a python program that get as input a path to .c file and then it compile its.

    The program will output OK to the screen if the compilation is sucessful, and BAD otherwise.

    I'm been trying to google it, but could not find anything. I've been also trying to run cmd within python with an argument of the compiling program but it didn't work.

    To clarify - I've already got a very specific compiler in my machine which I want to run. I dont want python to act as a compiler. Just get a code, run my compiler over it, and see what's the answer.

    • It should work on Linux server with python 2.4.

    Thanks