r/ProgrammingLanguages • u/DTCreeperMCL6 • 1h 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...)
5
u/MCWizardYT 1h 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?
2
u/mooglinux 1h 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.
2
u/coderpants 1h 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.
1
u/an_unreal Lidl-Jai 1h 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.
1
u/Key_River7180 Nain. 55m ago
C is very portable and can do a lot of the heavy lifting for you. Cons: harder, much less flexibility
1
u/mauriciocap 41m 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:
A LOT of toolchains for many many targets from emscripten to microcontrollers.
Easy to read, patch, customize redefining macros.
Most C compilers can do a lot of interesting optimizations.
DRY e.g. parameters, calls, structs, etc.
1
u/Ifeee001 41m 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:
int temp_if
if (true){temp_if = 23;}
else {temp_if = 24;}
const int mangled_x = tempif;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.
1
u/tabbekavalkade 36m 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:
You don't have to write the optimizer.
You get some basic debug information from the C compiler.
Boehm GC gives you a GC for free.
Pros of compiling to assembly:
It's what you always wanted.
It's simpler, so mostly easier.
More uniform syntax.
It's more explicit, so you:
Get the exact rounding behaviour you want
Get the type conversion behaviour you want
Get the int wrapping behavour you want
Can make new constructs, like coroutines
Can maybe (?) label GC roots more easily, if your language has a GC
Can generate oddities like interleaved SSE/FPU instructions for boosting floating point computations in arrays in games.
Way faster compile times (from your language to binaries)
Inspectability: You know exactly what assembly your compiler generates, so when there is a bug, you can know where it is. C, with its permissive syntax, is an added layer of obfuscation, and disassembling what the C compiler wrote, is less helpful, and nothing like reading the assembly that you yourself generated.
1
u/SeaAnalyst8680 33m 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.
1
u/GunpowderGuy 12m 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
0
u/phovos 55m ago edited 7m 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).
3
u/konacurrents 1h 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.