r/ProgrammingLanguages • u/DTCreeperMCL6 • 1d ago
Discussion Compiling to C
Ive found a lot of languages on this sub compile to c code instead of assembly or a backend. I'm curious what the advantages / disadvantages are to this. I know c is pretty optimized so is this an easy way to make a performant language or does it just make it simpler. I dont know c but I know assembly and some QBE so what are the pros and cons to directly compiling to assembly ( is it just more flexibility? etc...)
12
Upvotes
5
u/konacurrents 1d ago
C is the portable "assembly". Otherwise, what computer is the Assembly Code written for? Also you have to deal with the linker, etc. Lots of challenges (which original compilers had to deal with). What is "backend" in your statement? Is that the AST that a GNU code generator would use? That would be valid approach too.
6
u/tabbekavalkade 1d ago
Compiling to C looks simpler to people who already know C, but don't know assembly. With all the UBs and odd behaviours of C, it is NOT simpler. If you know how you would like your language to work, and C just doesn't work that way, you have a problem.
Pros of compiling to C:
Pros of compiling to assembly:
26
u/mooglinux 1d ago
Compiling to C is a far simpler task than compiling to assembly, and lets you lean on the immense amount of human effort that has gone into making C compilers. The benefits are similar if you compiled to llvm bytecode, you get all of the optimizations and device support of llvm.
23
u/MCWizardYT 1d ago
The advantage is that C compilers exist already that have been optimized to death over decades. Take Clang/LLVM and GCC as examples.
If you can generate decent C code, these compilers will optimize the shit out of it for you.
You also get the bonus of automatically supporting multiple architectures instead of having to learn the syntax and optimization tricks of the assembly for every platform you want to support.
It's a bit similar to why someone would want to target something like CIL or JVM bytecode instead of writing their own virtual machine: most of the work has already been done, why reinvent the wheel?
6
u/GunpowderGuy 1d ago
Advantages :
-You can output c that will run on any compiler
-compiling to c makes interop with c libraries, easier
Disadvantages:
-C might not support features your language may need . Such tail call optimization.
-Hooking rts such as garbage collections might be more difficult than with a custom backend
1
u/mamcx 20h ago
Another simpler option is compiling to web assembly.
3
u/coderpants 1d ago
The main advantages to me are inspectability, interoperability and cross-platform capabilities.
ie it's harder to read assembly, it's more painful to drop out to native code, and you need to handle different assembler/calling semantics for different platforms.
The main disadvantages Is that likely you are buying into the C execution model - ie stack based rather than something a bit more exotic - if you try to escape then you likely lose the inspectability and interoperability.
3
u/SeaAnalyst8680 1d ago
Quite a lot has been written about how C accidentally became the de facto language of interfaces. E.g., if you're using Rust or C# and want to call out to some other component - even one written in, say, Python - the bindings are written in terms of C "things" (raw pointers, null terminated strings).
Obviously there are lots of other better ways to interface two specific ecosystems, but C is the lowest common denominator that is always an option (including when you don't know how the other component was created, e.g. a closed source library).
The answer to why languages often transpile to C is the same as to why C is used for interfaces, but if you research the interfaces aspect, you'll probably learn a lot of useful stuff along the way. Including why, if you want your programming language to ever be broadly adopted, you need to provide the functionality for it to make use of and behave as a C component.
And of course, if your language is built on C, it's straightforward to make it interact as though it were C.
2
u/an_unreal Lidl-Jai 1d ago
Compiling to C is just really straightforward. You don't need any third-party library (like LLVM) with a massive API and a steep learning curve, or dive too deep into the low-level details of calling conventions, register allocation, object files, etc for rolling your own machine code generator.
Additionally, compiling to C gives you full tooling support out-of-the-box (e.g. for debugging your code), and it's pretty easy to cross-compile and port to other platforms.
Finally, debugging your generated code is also a lot easier than some of the other solutions. You can always look at the C file that you generated and debug that. The C compiler will also catch some of the more obvious mistakes that you make.
2
u/Key_River7180 Nain. 1d ago
C is very portable and can do a lot of the heavy lifting for you. Cons: harder, much less flexibility
2
u/Ifeee001 1d ago
One con that I often see mentioned is that it'll be difficult to express certain things in C. But I personally wouldn't say it's difficult. It'll probably be more difficult in assembly.
An example is if expressions. C doesn't have that. But you could just desugar it into an uninitialised temp variable declaration and update the values at the appropriate place inside the if block. Every path inside the if block must assign to the temp variable. The else block will/must contain an initialization too so you don't get garbage memory.
E.g. let x = 23 if true else 24;
Hypothetical C:
Ignore any errors. You could also take it a step further to "keep the scope clean" and take advantage of existing inclining optimization and make every if expression emit a function that'll return the result. That's probably over kill
Pretty much any common feature can be expressed in C if you're choosing it as your backend.
C also has a lot of hidden foot guns and undefined behavior.
2
u/vmcrash 1d ago
The advantage is that you can eliminate all the hard work done in the middle and backend. No need for lower-level IR, no need for register allocator, no need for creating optimal assembly code, no need for multiple backends for different targets.
2
u/honey-pony 1d ago
For context, my project is a compiled game scripting language.
The main reason I am currently compiling to C for my it is because having someone else write the backend saves a lot of trouble. I'm able to build for Linux, Windows, and WASM without writing basically any target-specific code. I can also use tcc for faster debug builds.
But the reason to choose C here over LLVM is not actually for any of those reasons (and in fact, I think I will have to swap to LLVM due to some semantic requirements of my language that aren't expressible in C). Instead, my main reason to prefer C as a backend over LLVM is because it makes it trivial to call C functions. LLVM still does not have a built-in way to handle the C ABI, meaning that you have to do a bunch of target-specific and very error-prone work just to get function calls to work, which is super annoying.
2
u/Public_Grade_2145 23h ago
Generating C is that supported by many toolchain many targets, including MCU platforms. It is easy way to produce efficient code since the toolchains have done the heavylifting for you.
If want to support on-device/on-the-fly compilation for the language, then compiling to C means that the implementation needs external toolchains. This is managable in hosted environment. It is harder to do it for MCU platforms, but it is not impossible (see: C Compiler On MCU, Is It Possible?). As comparison, micropython have its own native emitter, in addition to its bytecode target.
Though, if the intended usage is compilation/cross-compilation, then these are not problem. :)
One advantage of directly emitting assembly is that you have exact control over the internal ABI. This is convenient for GC implementation for managed languages.
Another advantage of directly emitting assembly/bytecode is that it provide option of writing your own. For example, I've my scheme compiler compiling small program to native armv6-m on rp2350, since my implementation emit assembly, then the gap is to write the assembler.
2
u/dnpetrov 8h ago
Compiling to C is somewhat simpler, except when it isn't: you have to care about UB (which means: C compiler can and will do anything it wants depending on particular compiler version, compilation options, target architecture, and so on). Basically, you need to be aware of the C semantics, which has its own dark corners. Other than that, you'll need to implement missing pieces of the language runtime. But you'll need to do that on any target platform, and the "C abstract machine" is just yet another target platform in that regard.
There are production compilers that compile via C. For example, hardware simulators (which are actually Virolog to x86 compilers) do that, mostly because of implementation concerns. Same with some SQL engines.
MATLAB has an M language to C compiler, because C code is often a starting point for DSP or hardware implementation.
Several Scheme language implementations compile to C.
1
u/mauriciocap 1d ago
Think of C as a virtual machine better than the one accepting e.g. x86 assembly. Notice x86 assembly can also be seen as a VM running over RISC assembly, etc.
Some advantages of generating C:
1
u/dreamingforward 1d ago
One advantage is that you can now compile to nearly any processor.
1
u/EggplantExtra4946 25m ago edited 17m ago
The only advantage is that it's quick and dirty. You will get more performance and as much portability as C by emitting the IR of a compiler backend.
If your language is like all the other boring languages control-flow and function/stack wise, you're fine with C, but the moment you want exceptions (that work well with the following), coroutines/green theads/etc.., backtracking, threaded interpreters, continuations, TCO, stack frames on the heap, bounds checking the function call stack, etc..., good luck with C.
Seriously, what's the point in making a new "systems language" if it's not even expressive enough to implement a library for doing concurrency and asynchrony stuff without requiring you to write assembly? For example, implementing go routines as a library, the actor model of the BEAM VM or a library similary to libuv. What's the point you may ask since all those already exists: good composibility without a ton of glue, meaning the problem a programming language is supposed to solve.
Also you might want to avoid C's UB and have more data primitives, SIMD, bit manipulation, etc... Particular compilers have intrinsics but then the orignal pros for targeting C as opposed to a proper backend disappear.
0
u/phovos 1d ago edited 1d ago
What "C-like" ultimately portends is like Assembly + the "Abstract machine" + "Call by Reference/Call by value semantics".
In other words it is [pre-compiled] assembly but made with respect to each platforms abstract machine while dealing with any memory/bus hardware/bandwidth/etc. [2s compliment? etc.] (so writing the instructions per the platform, and changing the elements of the program that change with respect to those changes) changes.
(this is for C99 and onward, the 'abstract machine' was not fully parameterized in early years of C... actually I think its C89 and forward lol but I just always use C99)
edit: downvoter fight me you can't be more accurate or descriptive than the above without investing actual time or money in it (Oh, it must be; C89 fans not withstanding, probably just old-hats, any new young adherent will devote themselves to the C99 catechism, or newer).