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.

Answer from hoefling on Stack Overflow
Discussions

how to compile and run C code with embedded python script? - Stack Overflow
The documentation here shows how to tell the compiler where python headers and libraries are located. ... If your python installed scripts in a different place, you will have to change the /opt/bin to the place where ...-config is really located. From your whereis trace, it could be /usr/bin. More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 30, 2013
compiling a c program to use in python code - Stack Overflow
I have a c program that I need to compile and use in the middle of a python code. it is not c++ program so I assume I should change this syntax for compiling because I get a lot of errors related t... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Compile and execute C program in Python using Windows - Stack Overflow
Sign up to request clarification or add additional context in comments. ... Thank you Laurenz. I installed gcc compiler and attempted to compile through the windows command prompt but there are many errors returned which I assume are related to the makefile as you mentioned. Now that I realise the complexity of the task I will likely compile the multiple variations of the program that I need in Unix before running my python ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c++ - How to run c code within python - Stack Overflow
The code should run as it would ... create and edit variables so that python can use it. If necessary, the code can be pre-compiled into the code = """something""". Sorry for all the requirements but if you can make the c code run in python then that would be great. Thanks in advance for all the answers.. ... @Karthikeyan.R.S I am not trying to run code externally from python but ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 11, 2017
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to compile and run c programing file using python language - YouTube
In this discussion you will see, How to compile c file using python language, how to run c programing file using python package. using subprocess package to ...
Published: August 1, 2020
๐ŸŒ
Quora
quora.com โ€บ How-do-I-write-a-Python-script-to-run-a-C-program
How to write a Python script to run a C program - Quora
Answer (1 of 6): I assume you want to both compile and run the code! You can follow following steps: Since i am using windows to run the "gcc" command i did these settings: 1. Install DEV-CPP 2. Now set the path of "gcc" file in your environmental variables i.e. "C:\Program Files (x86)\Dev-Cpp\M...
๐ŸŒ
Readthedocs
reptate.readthedocs.io โ€บ developers โ€บ python_c_interface.html
Tutorial: Interfacing Python and C code โ€” RepTate 1.4.0 documentation
Fortunately, there are many solutions available to write code that will run fast in Python. We can cite Cython or Numba that transform Python code into C executable and require minimal addition to the existing Python code. There is also Ctypes that provides C compatible data types, and allows calling functions from external libraries, e.g. calling pre-compiled C functions.
๐ŸŒ
Medium
medium.com โ€บ gitconnected โ€บ write-compile-and-run-c-code-using-python-the-magic-of-pythoc-e503830a43a5
Write, compile and run C code using Python: The Magic of PythoC
April 8, 2026 - I came across an interesting library the other day that I hadnโ€™t heard of before. PythoC is a Domain-Specific Language (DSL) compiler that allows developers to write C-like programs using standard Python syntax.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ calling-c-functions-from-python
Calling C Functions from Python | DigitalOcean
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation. ... Full documentation for every DigitalOcean product. ... The Wave has everything you need to know about building a business, from raising funding to marketing your product. ... Scale up as you grow โ€” whether you're running one virtual machine or ten thousand.
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ How-do-I-compile-and-run-multiple-C-or-C-by-using-Python-code-Subprocess-call-gcc-cprogram-c-subprocess-call-a-out-like-this-in-this-program-it-just-take-one-file-but-I-want-multiple-files-to-do-like-this
How to compile and run multiple C or C++ by using Python code - Quora
Answer: It Depends (tm). But I struggle to work out why you would choose to create varying C/C++ source code, then choose python to compile and run that code; I could understand either one of those choices, but not both. But, as someone who has asked strange questions [on StackOverflow & others]...
๐ŸŒ
CSEstack
csestack.org โ€บ home โ€บ calling c functions from python [step by step procedure]
Calling C Functions from Python [Step by Step Procedure]
August 15, 2019 - ... You can not do it directly. You can execute a compiled C program (.exe file) from the Python program using a subprocess module by running the executable file using subprocess.open() method in Linux.
๐ŸŒ
Quora
quora.com โ€บ Is-it-possible-to-compile-Python-programs-into-C-code-and-run-them-using-this-method
Is it possible to compile Python programs into C++ code and run them using this method? - Quora
Answer (1 of 3): Sort of, but not really. You can certainly use specialised tools that allow you to compile a subset of Python into something that resembles C/C++ code, and compile it to run at roughly similar speed. Sometimes this works great. It is also possible to write Python code that make...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62439581 โ€บ compile-and-execute-c-program-in-python-using-windows
Compile and execute C program in Python using Windows - Stack Overflow
I need to iteratively edit, recompile and run a C program called sum_subgiants.c through Python (using Spyder on Windows). I am using a python code that has previously worked on my colleague's Mac....
๐ŸŒ
Quora
quora.com โ€บ How-can-I-run-C-code-in-Python
How to run C code in Python - Quora
Answer (1 of 8): I am assuming that you want to run your C code using Python language(interpreter) not a Python script to run a .c or .exe file. You can do it by calling subprocess for that you will need subprocess and os module. [code]import sys import subprocess import os prog = r''' #includ...
๐ŸŒ
howtos
wgilpin.com โ€บ howto โ€บ howto_cython.html
Running a C/C++ executable from within Python, without any IO | howtos
Now - Compile your executable, and then use the subprocess library. Then, in your Python script, use some variant of this: def test_no_io(): ''' Run a process that takes no input and produces no output ''' ## Shell=False helps the process terminate process = subprocess.Popen("./hello", shell=False) ## Get exit codes out, err = process.communicate() errcode = process.returncode print(errcode) process.kill() process.terminate()
Top answer
1 of 2
2

As somebody else already pointed out, to run C/C++ code from "within" Python, you'd have to write said C/C++ code into an own file, compile it correctly, and then execute that program from your Python code.

You can't just type one command, compile it, and execute it. You always have to have the whole "framework" set up. You can't compile a program when you haven't yet written the } that ends the class/function/statement 20 lines later on. At this point you'd already have to write the whole C/C++ program for it to work. It's simply not meant to be interpreted on the run, line by line. You can do that with python, bash/dash/batch, and a few others. But C/C++ definitely isn't one of them.

With those come several issues. Firstly, the C/C++ part probably needs data from the Python part. I don't know of any way of doing it in RAM alone (maybe there is one, but I don't know), so the Python part would have to write it into a file, the C/C++ part would read and process it, then put the processed data into another file, and then the Python part would have to read that and continue.

Which brings another point up. Here we're already getting into multi-threading territory, because the moment you execute that C/C++ program you're dealing with a second thread. So, somehow, you'd have to coordinate those programs so that the Python part only continues once the C/C++ part is done. Shouldn't be a huge problem to get running, but it can be a nightmare to performance and RAM if done wrongly.

Without knowing to what extent you use that program, I also like to add that C/C++ isn't platform-independent like Python. You'll have to compile that program for every single different OS that you run it on. That may come with minor changes to the code and in general just a lot of work because you have to debug and test it for every single system.


To sum up, I think it may be better to find another solution. I don't know why you'd want to run this specific part in C/C++, but I'd recommend trying to get it done in one language. If there's absolutely no way you can get it done in Python (which I doubt, there's libraries for almost everything), you should get your Python to C/C++ instead.

2 of 2
0

If you want to run C/C++ code - you'll need either a C/C++ compiler, or a C/C++ interpreter.

The former is quite easy to arrange (though probably not suitable for an end user product) and you can just compile the code and run as required.

The latter requires that you attempt to process the code yourself and generate python code that you can then import. I'm not sure this one is worth the effort at all given that even websites that offer compilation tools wrap gcc/g++ rather than implement it in javascript.

I suspect that this is an XY problem; you may wish to take a couple of steps back and try to explain why you want to run c++ code from within a python script.

๐ŸŒ
Medium
medium.com โ€บ nabla-squared โ€บ how-to-use-c-code-in-python-582491e572d1
How to use C code in Python. โ€ฆ and should we do this? | by Dorian Lazar | Nabla Squared | Medium
May 31, 2021 - If all you want is just to speed up your Python program, then there is actually an easier way rather than writing certain parts of your program in C. You can just use PyPy instead of Python when executing your app. PyPy is an alternative implementation of the Python programming language which uses just-in-time compilation to speed up the same python code with little or no changes to your code. You can download and install it from here.
๐ŸŒ
Klein Embedded
kleinembedded.com โ€บ home โ€บ calling c code from python
Calling C code from Python - Klein Embedded
January 31, 2023 - Then build the DLL by first running cmake -Bbuild -G"MSYS Makefiles" (I am using MSYS on Windows, but use whatever generator you have, of course) and then cmake --build build. We should end up with a libscale.dll in the build folder which we are going to use in the Python script.
Top answer
1 of 2
128

I want to invoke those C function or executables in python. Is that possible.

Yes, you can write C code that can be imported into Python as a module. Python calls these extension modules. You can invoke it from Python directly, an example from the documentation:

Python Code

import example
result = example.do_something()

C Code

static PyObject * example(PyObject *self)
{
    // do something
    return Py_BuildValue("i", result);
}

If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.

You build it as a shared library *.dll or *.so You can also investigate using distutils to distribute your module.

If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?

If you write a *.exe then you are doing the opposite (invoking Python from C). The method you choose (exe vs shared library) depends on if you want a "C program with some Python" or a "Python program with some C".

Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?

Python reads *.py files and compiles to *.pyc bytecode files when you run it. The bytecode is then run in the Python virtual machine. This means "executing the same file is faster the second time as recompilation from source to bytecode can be avoided." (from the Python glossary) So if you haven't edited your *.py files, it will run the *.pyc. You can distribute *.pyc files without *.py files, however they are not encrypted and can be reverse-engineered.

2 of 2
16

You don't necessary need to extend Python (which is not trivial, btw), but can use foreign function interface such as ctypes.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how is python able to use c code?
r/learnpython on Reddit: How is python able to use c code?
September 18, 2021 -

I was always curious how python modules in c work. I know how to write and use a python c module, but i dont know how it works internally. Can anyone put me in the right path where can i start, an article or sthm or try to explain. And are there any simple tutorials to implement that sort of thing. Like calling .so files from your language etc...

Top answer
1 of 1
3
There is an API in the C that you can use to interact with Python objects from C code, which is the same API that python uses internally to bootstrap itself in many cases. There are good guides in the official python docs for how to make a python module in C in detail, but the overview of how it's done is: Create a c source file Include the Python.h header file, which exists on any system with the python interpreter installed. There are functions and macros in the Python.h header that allow you to create a python module "object", which can be imported, and to specify which functions should be part of that object, and for each function, you can specify it's python function signature, although from a C perspective, all the values passed into a python function are just python objects (pointers to a PyObject struct) The PyObject structure is the fundamental data type inside the python interpreter. It is a polymorphic struct, which is really neat. You can implement polymorphism and object orientation inside of C with some neat struct casting tricks, and that's what python does. Therefore, there are macros to convert the PyObject struct coming into your function to a PyListObject struct, for example, and then there are more C APIs for doing what you need to do to a list (append, insert, delete, etc.) Now, once your C code is all written up, you need to compile it. This would be tricky, except that python's setuptools (setup.py) has utilities for including C extensions in your library. So, you can just compile it through that tool while mostly ignoring the complexity of compiling and linking manually. At the end of the day, if you created a module named foo in C, you should be able to simply import and use it like any other python module. For example, the csv module is implemented entirely in C, although you'd probably never know it!