Let me explain a trick. Jinja2 is a template script that can generate text from templates. What you need to do is write your C code template main.c.j2:


#include <stdio.h>

int main()

{

    printf("hello {{name}}.\n");

    return 0;

}

then you can transform it into C code with the trans.py:


import os

from jinja2 import PackageLoader, Environment, FileSystemLoader



TemplateLoader = FileSystemLoader(os.path.abspath("."))

env = Environment(loader = TemplateLoader)



template = env.get_template("main.c.j2")



print(template.render(name = "Jack"))

run python trans.py and you will see this C code on screen:


#include <stdio.h>

int main()

{

    printf("hello Jack.\n");

    return 0;

}

That's real C code, {{name}} is replaced into Jack. See the Jinja2 doc for more interesting features.

Answer from alven darthy on Stack Overflow
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
PythoC: A new way to generate C code from Python | InfoWorld
December 19, 2025 - A new project, PythoC, takes a different approach. It uses type-hinted Python to programmatically generate C code—but chiefly for standalone use, and with many more compile-time code generation features than Cython has.
🌐
GitHub
github.com › cogu › cfile
GitHub - cogu/cfile: A python C code generator
import cfile C = cfile.CFactory() code = C.sequence() code.append(C.sysinclude("stdio.h")) code.append(C.blank()) char_ptr_type = C.type("char", pointer=True) code.append(C.declaration(C.function("main", "int", params=[C.variable("argc", "int"), C.variable("argv", char_ptr_type, pointer=True) ]))) main_body = C.block() main_body.append(C.statement(C.func_call("printf", C.str_literal(r"Hello World\n")))) main_body.append(C.statement(C.func_return(0))) code.append(main_body) writer = cfile.Writer(cfile.StyleOptions()) print(writer.write_str(code))
Starred by 91 users
Forked by 25 users
Languages   Python 99.7% | Batchfile 0.3% | Python 99.7% | Batchfile 0.3%
Discussions

python - Generating C code from script: how to template? - Stack Overflow
I'm looking for a way to insert some auto-generated code into C source files. The code generation is in python and that's not a problem, the trick is how to replace/update blocks of code in existi... More on stackoverflow.com
🌐 stackoverflow.com
How to generate C code from Python? - Stack Overflow
I am writing an embedded algorithm. Currently I have lookup tables that are hard-coded: static const int32_t sine[65536] = { ... } The algorithm should be portable on different platforms but,... More on stackoverflow.com
🌐 stackoverflow.com
C++ code generation with Python - Stack Overflow
Can anyone point me to some documentation on how to write scripts in Python (or Perl or any other Linux friendly script language) that generate C++ code from XML or py files from the command line. ... More on stackoverflow.com
🌐 stackoverflow.com
syntax - How to generate C++ code? (probably WITH (not FROM) Python) - Software Engineering Stack Exchange
For a scientific simulation I need to write some computations in C++. Since this became extremely tedious, I built myself a small code generator: In a scripting language (Python) you put together a More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 23, 2016
🌐
Google Groups
groups.google.com › g › cython-users › c › XvCV-TKKnEw
Generate C code from Python.
You should also take a look at Shedskin. It only supports a statically analysable subset of Python (and not all stdlib modules are supported), but for what it supports, it generates very good stand-alone code (C++).
🌐
Stack Overflow
stackoverflow.com › questions › 49153647 › how-to-generate-c-code-from-python
How to generate C code from Python? - Stack Overflow
in: $(IN) $(IN): build/headers/%: src/%.in mkdir -p $(dir $@) PYTHONPATH=.:$$PYTHONPATH mako-render $< > $@ || true · I like this solution because I can easily generate C code from Python results:
🌐
SymPy
sympy.org › scipy-2017-codegen-tutorial
Automatic Code Generation with SymPy
use the SymPy code generation routines to output compilable C code and use Cython to access these functions in Python,
Find elsewhere
🌐
Python
python.org › about › success › cog
Cog: A Code Generation Tool Written in Python
We could then use this general purpose tool to solve our specific generation problem. The tool I wrote is called Cog. Its requirements were: We needed to be able to perform interesting computation on the schema to create the code we needed. Cog would have to provide a powerful language to write the code generators in.
🌐
GitHub
github.com › cython › cython
GitHub - cython/cython: The most widely used Python to C compiler · GitHub
Cython translates Python code to C/C++ code, but additionally supports calling C functions and declaring C types on variables and class attributes. This allows broad to fine-grained manual tuning that lets the compiler generate very efficient ...
Starred by 10.7K users
Forked by 1.6K users
Languages   Cython 51.6% | Python 41.9% | C 6.2% | C++ 0.2% | Shell 0.1% | Starlark 0.0%
🌐
GitHub
github.com › inducer › cgen
GitHub - inducer/cgen: C/C++ source generation from an AST
cgen offers a simple abstract syntax tree for C and related languages (C++/CUDA/OpenCL) to allow structured code generation from Python.
Starred by 171 users
Forked by 35 users
Languages   Python 100.0% | Python 100.0%
🌐
Sokol WebGL
floooh.github.io › fips › docs › codegen
Code Generation | Fips Docs
Fips makes it easy to generate C/C++ source code by running Python scripts during the build process. Special care has been taken to make code generation flexible so that it is useful for many different scenarios.
🌐
PyPI
pypi.org › project › csnake
csnake
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Top answer
1 of 8
16

If you want to do this simply with just standard Python stuff you might try making template files that use the Python 3 style string formatting. For example, a class template might look something like this:

{className}::{className}()
{{
}}

{className}::~{className}()
{{
}}

{className}::{className}(const {className}& other)
{{
}}

{className}& {className}::operator=(const {className}& other)
{{
    return *this;
}}

Then your Python code is super simple:

d = {}
d['className'] = 'MyCPlusPlusClassName'
with open(yourTemplateFile, 'r') as ftemp:
    templateString = ftemp.read()
with open(generatedFile, 'w') as f:
    f.write(templateString.format(**d))

Of course you can add lots of other fields alongside 'className' using the same trick. If you don't need stuff like conditional code generation you can get a lot of mileage out of something this simple.

2 of 8
2

I'm afraid you will not find an already-built in solution that takes your particular xml or python files and transforms them onto your required output "out of the box".

You will have to implement the parsing, the data treatment and output yourself. Not all by yourself, though; here are some pointers regarding the parsing and output.

Python comes with 2 different XML parsers (SAX and DOM -scroll down to see some examples). You will have to use one of them in order to read the source files.

For generating the output more easily, you can probably use a templating library, such as StringTemplate, or just generate the code manually, if it's small.

🌐
GitHub
github.com › JhnW › devana
GitHub - JhnW/devana: Python package to parse and generate C/C++ code as context aware preprocessor.
Devana is a python tool that make it easy to parsing, format, transform and generate C++ (or C) code. This tool uses libclang to parse the code. Fundamental problems, bugs and missing features of libclang are fixed in Devann's internal code.
Starred by 18 users
Forked by 6 users
Languages   C++ 51.4% | C 42.9% | Python 5.4% | CMake 0.3% | C++ 51.4% | C 42.9% | Python 5.4% | CMake 0.3%
🌐
Medium
medium.com › @widyanandaadi22 › pythons-hot-new-tool-generate-c-code-and-turbocharge-your-apps-155a019fd554
Python’s Hot New Tool: Generate C Code and Turbocharge Your Apps | by Made Adi Widyananda | Feb, 2026 | Medium
February 12, 2026 - By generating C code that calls these libraries directly, developers can avoid the overhead of the Python C API. * Code optimization: The code generation process can automatically perform various optimizations that would be difficult or impossible to do manually.
🌐
CodeProject
codeproject.com › Articles › 571645 › Really-simple-Cplusplus-code-generation-in-Python
Really simple C++ code generation in Python - CodeProject
April 3, 2013 - from CodeGen import * cpp = CppFile("test.cpp") cpp("#include <iostream>") with cpp.block("void main()"): for i in range(5): with cpp.subs(i=str(i), xi="x"+str(i+1)): cpp('int $xi$ = $i$;') cpp.close() ... The substitutions are valid within the Python with block, which can be nested. To finish off here's a more complicated example to generate the following code:
Top answer
1 of 2
6

So you want to translate some (yours) domain specific language (DSL) to some flavor of C++. I am doing exactly the same in my GCC MELT implementation (inactive as of 2017). It is a Lisp-y domain specific language to customize the GCC compiler. See also this answer giving slightly more details, and this one giving relevant references.

Here are some advice; I cannot be more specific because I have absolutely no idea what your domain specific language is for. Is it Turing-complete (perhaps accidentally)? Probably yes! Read also this draft report.

  • if you never studied it, study compiler techniques (including lexing & parsing). They are highly relevant.

  • read Scott's book Programming Language Pragmatics (at least for inspiration).

  • consider (instead of developing your own DSL) embedding some existing interpreter, perhaps Guile or Lua. It might be considerably simpler.

  • be aware that designing and implementing a passable DSL which is compiled (perhaps to C++) is a lot of work (years!). Read the mythical man month, Hofstadter's law, etc... Perhaps you want (or not) to bootstrap your language implementation...

  • if your DSL is somehow useful (e.g. you are not the only one writing scripts in it), be aware that eventually some crazy user would code large scripts (many thousands lines) in it. So design the language seriously!

  • first, you need a well defined (in your head!) representation of the abstract syntax tree (which might not be a tree, but a graph) of the generated C++ code and you should build (in memory) the AST before emitting the corresponding C++ code

  • you might want to emit #line directives (referring to positions inside your DSL scripts). It is very useful (for debugging) but emitting them is quite hard.

  • you might need several other internal representations, between the DSL source and the generated C++ code, and your C++ code generator (actually a specialized compiler) is transforming some representations into another ones, and finally into an AST which is emitted as C++ code.

  • you should care about the memory model; so read about garbage collection techniques (at the very least, for terminology and concepts), see the GC handbook. You probably don't want a stupid user script to crash the computer or the process. So you need to handle memory (& memory leaks).

  • perhaps you might consider, instead of generating C++ code, to use JIT compiling techniques: GCCJIT, LLVM, libjit, asmjit, ...

  • perhaps SciLab, R, Octave, Julia might be relevant for your work (because they might avoid you to start your own DSL)

  • On Linux specifically, you might generate C++ code in some temporary file, compile it into a plugin (read Drepper's paper How To Write Shared Libraries and about Invoking GCC and see elf(5)) , then dlopen(3) it (and use dlsym(3) to get function pointers). Read then the C++ dlopen mini-howto. The RefPerSys project is doing that.

The CLASP project should be relevant: it is about Common Lisp and molecular chemistry simulation.

2 of 2
2

Do you need to generate C++, or compiled code? You can leverage LLVM to produce compiled output from scripted tooling. The clang intermediate language is verbose but powerful - its what C++ code (or any other supported language) gets parsed into before compilation. Alternatively you can generate C++ from tools that still leverage the Clang parser, so instead of manipulating the text, you manipulate the internal AST the parser holds.

For an example, look at cmonster, which is a (rudimentary) python wrapper for clang's C++ parser.

🌐
Mark's Software Blog
markvtechblog.wordpress.com › 2024 › 04 › 28 › code-generation-in-python-with-jinja2
C++ Code Generation using Python and Jinja2 | Mark's Software Blog
January 31, 2026 - This post shows a minimal, working code generator: a YAML “message spec” plus Jinja2 templates that generate C++ .h/.cpp files, with a small Python script you can copy and adapt. Throughout my care…
🌐
CodeConvert AI
codeconvert.ai › python-to-c-converter
Free Python to C Converter — AI Code Translation | CodeConvert AI
The AI understands both Python and C idioms and produces natural-looking code. ... Signing in unlocks CodeConvert AI's Pro tool, which includes more powerful AI models, an integrated chat assistant, code execution, personal notes, conversion history, and an enhanced interface. Every account gets 5 free credits per day to explore the full Pro experience. Code ConverterCode GeneratorCode ExplainerComment RemoverCode to PDF