1

In a project that I have been asked to revise, there is a segment of code that is tantamount to just generating a set of assembly instructions, writing them to a file, and then compiling it with the gcc compiler.

My question is, is there any way to link in a library that would do this work for me via an exposed API call? I need 1-1 equivalence to the following command:

gcc -m32 -c -o objfile generated_asm.asm -masm=intel

Adam Miller
  • 1,756
  • 1
  • 25
  • 44

2 Answers2

2

You cannot do exactly that. You might fork the GCC compilation command. It is probably operating system specific, I'm supposing you are on Linux (or some other POSIX system).

However, there are alternatives:

  • using asmjit to generate x86 machine code in memory
  • using tinycc and its libtcc library (which can compile a string containing C or asm code; beware, the compiled machine code is slow since unoptimized)
  • using a JIT library like libjit, or LLVM, or GNU lightning
  • coding in a metaprogramming language like Common Lisp (e.g. SBCL) or MetaOcaml

Also, you could simply fork a GCC compilation of some generated C file genfoo.c into a shared object (gcc -Wall -O -fPIC genfoo.c -shared -o genfoo.so) then dynamically loading with dlopen the ./genfoo.so file (see also this)

PS. Next GCC 5.0 release will have a JIT library (libgccjit).

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

Generally, no, because Unix insisted we think of everything as text strings (including command lines). And we all accepted Unix.

Technically GCC is just giant subroutine with a big parameter list.

The fact that you get to it though a text string is a stupid design decision we all made by dumping Multics and/or LISP machines. On these systems, subroutines (even big ones) are all called natively, and thus really compose.

With Multics, the compiler is (well was, Multics is pretty dead) a subroutine you can call. (Yes, there was a command line interface that could also make that call, so people could invoke it).

Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
  • I disagree with the "GCC is just giant subroutine with a big parameter list" phrase. There is no common data (or closed values) between GCC and the invoking process (since they are separate processes with separate address spaces) – Basile Starynkevitch Dec 02 '14 at 12:07
  • 1
    Just goes to show what a clumsy parameter passing process Unix commands have. – Ira Baxter Dec 02 '14 at 16:53