title: Compiling C code generated at runtime within Python
body: <p>I am generating some C code at runtime within Python. What is the best way to compile this code into <em>something</em> that can be called from Python? I know that I can do:</p>
  
  <pre class="lang-py prettyprint-override"><code>import subprocess
  from ctypes import cdll
  subprocess.run(['gcc', '-shared', '-o', 'tempfile.so', 'tempfile.c'])
  main_function = cdll.LoadLibrary('tempfile.so').main
  </code></pre>
  
  <p>But it is a lot of work to solve all the edge cases and portability problems related to this solution. I was hoping this was a common enough issue that it had a standard solution that abstracts the difficult parts away (finding an installed compiler, writing to a temporary directory, handling errors, cleaning up garbage, etc.).</p>
  
  <p>I found that <a href="https://pypi.org/project/weave/" rel="nofollow noreferrer"><code>weave</code></a> can do this, but it is Python 2 only. I am on Python 3.</p>
  
  <p>This is not a question about how to import already-compiled C code. I am familiar with <code>ctypes</code>.</p>
  
  <p>This is also not a question about generating different code that can be handled easier. I am familiar with <code>numba</code> and <code>cython</code> which compile Python code, but unless they have a hidden feature to accept pure C code, that won't work because the C code is being generated by an external tool.</p>