r/ProgrammingLanguages • • 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

45 comments sorted by

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.

1

u/DTCreeperMCL6 1d ago

Like llvm or QBE

2

u/Big-John-Havercamp 1d ago

I transpiled to C when I wrote by hand because I could check it myself. 

I played with an LLM to target LLVM and that worked too, but I definitely didn't write that myself. 

If you have an AST, it's not trivial, but it's pretty mechanical. 

1

u/konacurrents 1d ago

Thanks. I haven't dealt with LLVM or QBE (had to look it up). It seems these have similarities to the GNU code generator/generator. But the overall approach is you leverage those code generators. Writing in C (or say javascript) as the intermediate language is obviously a proven approach.

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:

  • 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/DTCreeperMCL6 1d ago

Okay thanks, your comment is the only one Ive seen so far that says any of the advantages of using assembly. I know assembly but not too well and I only know one platform so I might try to learn llvm instead. I dont think I want my language to be a c wrapper.

2

u/WittyStick 1d ago edited 1d ago

GP missed out the disadvantages though - if you want your code to be efficient, you have to do instruction selection, instruction scheduling, register allocation, peephole optimization, and so forth.

These are each individually difficult problems, and they're often dependant not only on the ISA - but every CPU family may have different timings, OoO behavior, different cache behavior, branch prediction, and the list goes on. The timings are often not even published and need to be reverse engineered (eg, like uops.info, which are community efforts).

You can emit naive assembly without much trouble - but you are simply never going to match the efficiency of code produced by established C compilers (namely, GCC, Clang, ICC, MSVC, and a few other minor ones).

Moreover, these compilers will beat hand-written assembly 90% of the time because they are aware of these timings - you would have to look them up, because you certainly won't remember them all - and your finely optimized hand-written assembly is optimized only for one CPU family. The 10% where you can beat the compiler is usually some tightly optimized SIMD loop - where the compiler falls short because it isn't magic. For these cases, you can simply embed assembly in C to get the optimizations that the C compiler might miss.

There's a reason everyone just plugs in LLVM - they want their compiler to produce efficient code - but they don't have two decades or more that would be needed to even get close to parity with LLVM's optimizers - which are the culmination of hundreds of thousands of man hours of work, by experienced engineers, each specializing in particular parts.

Compiling to C is a cheap way to get these optimizations without having to learn the specifics of LLVM or GIMPLE. It's not the most efficient in terms of compile times because you have additional printing, parsing and the front-end optimizations done by Clang - whereas emitting LLVM IR involves fewer stages, or compiling directly through LLVM or GIMPLE's APIs is more efficient and avoids the round trip of printing/parsing.

1

u/DTCreeperMCL6 21h ago

Rahh. I dont know Im back and forth, I like the idea of compiling it without c more and Im not too worried about it being super optimized, but if I ever want anyone to use my language they will probably want those optimizations it provides. Maybe I will implement compiling to c first but add a directly to assembly option as well just for fun because thats something I want to do.

1

u/genericallyloud 19h ago

This is what LLVM IR is for instead of assembly or C

1

u/honey-pony 3h ago

In my opinion, compiling to C is a pretty good starting point for writing compilers. It helps you start to think in the way that you'll need to think for any kind of backend you write but has the advantage that it's very easy to understand your compiler's output.

If you're thinking of eventually writing your own assembly backend then you'll probably want to structure your compiler in a target-agnostic way anyway, in which case C will just be one more target to implement.

For my own project (which currently compiles to C) I think I will need to switch to LLVM for some of the reasons I've discussed in this thread but also for debugging support and for better GC integration. This does seem like it'll be pretty tricky for me so it's definitely true you can end up with a backlog of work to do if your compiler isn't super target-agnostic and you end up needing to swap away from C eventually. However, I think it's better to have a vertical slice of your compiler up and running so that you can really start hacking on it, then it is to agonize too much about backend choice. And C is a great way to get something working very quickly.

2

u/kwan_e tonal-lang 22h ago

> With all the UBs and odd behaviours of C, it is NOT simpler.

You think you get bounds checks, type checks, and lifetime checks in Assembly? Assembly cannot be better than C with regard to UB. You just won't get notified of them.

And if you say "well, all the checks will be handled by my high level language"... so would the language with the C backend.

Compiling to C isn't just a simple text transformation. The high level stuff you would implement for your assembly backend will also be implemented in a language with the C backend. And if you aren't building in those checks in your high level language, you have worse UB.

2

u/MadocComadrin 20h ago

More uniform is debatable. What if I want cross-platform compilation? Now it's not uniform at all: I need to take into account in the very least Intel/AMD, ARM, and maybe RISCV. SIMD Instructions can make this worse if you want to support older processors.

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?

7

u/Norphesius 1d ago

Cons: You are restricted to the C memory model, C's ABI, C's build quirks, and need to be vigilant about UB when generating code. 

It might not seem like that big a deal, after all you can approximate almost any feature you want in your langauge (and mask over C particulars) with enough generated C, but usually if you use C you'll want to make use of the C standard library. Now you have to make C interop a big part of your language, even if that doesn't really fit with the paradigm (functional, GC, memory safety, etc.). Even if you somehow reimplement glibc in your language natively, people will still want to interop with other C libraries, and would be confused if your lanagauge compiled to C but didn't have good interop with it.

And one very contextual downside: If you're building a language as a learning exercise, you may want to use it as an opportunity to learn assembly.

5

u/omniuni 1d ago

I found the good middle ground is LLVM IR. Much more flexible, and very easy to bind to C libraries if needed.

5

u/kwan_e tonal-lang 22h ago

> You are restricted to the C memory model

You are not restricted to the C memory model. You can implement whatever bounds checks, GC or smart pointers or lifetime tracking in your high level language, or call out to whatever GPU you want.

Say if your language has RAII, you would generate all the necessary constructor and destructor call when compiling to C, because your language has that information. That would be the job of YOUR compiler. You don't need C support for RAII to generate RAII code. So you would not be restricted to C's memory model.

4

u/honey-pony 19h ago

You are definitely restricted to C's memory model (where "memory model" refers to the available semantics for loads/stores, etc).

For example, you don't have access to anything equivalent to LLVM's 'atomic unordered' load/store. This is actually pretty bad when trying to implement bounds checks... in order to correctly implement bounds checks in the presence of data races (Java-style), I'm pretty sure the only correct way in C is to either use relaxed atomic loads or volatile loads, both of which are worse than the LLVM unordered atomic load.

1

u/kwan_e tonal-lang 18h ago

https://llvm.org/docs/Atomics.html

The only way that memory_order_relaxed is "worse" than atomic unordered, is that it has some synchronization that would make it slower.

Apparently not so different:

Notes for code generation

Code generation is essentially the same as that for unordered for loads and stores. No fences are required. cmpxchg and atomicrmw are required to appear as a single operation.

Unordered atomic loads also doesn't seem so flash for Java under ARM64:

Note that this guarantee is cheap on common platforms for loads of a native width, but can be expensive or unavailable for wider loads, like a 64-bit store on ARM. (A frontend for Java or other “safe” languages would normally split a 64-bit store on ARM into two 32-bit unordered stores.)

And again, if it is really necessary, there's nothing stopping people from using inline ASM in C to use these unordered atomics, wrap them in a forced-inline function (or macro) and generate those calls when compiling the HLL. The HLL implementation would, again, do all the keeping track of generating the calls to that code.

1

u/honey-pony 17h ago edited 17h ago

I mean, they are worse in that LLVM will (in its current version) not eliminate redundant loads to the same memory location, which seems bad as it will also inhibit further optimizations: https://godbolt.org/z/js9c41ob4

I don't think you can get something similar in C no matter what you do. If you use inline assembly, is the compiler going to be able to do redundant load elimination on those assembly blocks? It seems pretty unlikely to me.

You could of course write your own optimizer to fix this problem but at that point, why even bother emitting C?

For reference, the kind of scenario where this is important in my own work is I want to emit bounds checks that look like this:

uint64_t index = <expression>;
if(index >= arr->length) { panic(); } // Note: arr->length never changes
T object = arr->contents[index];

But we're not allowed to just generate this without atomics/volatile, because the C compiler is allowed to (and will sometimes) rewrite it like so:

uint64_t index = <expression>;
if(index >= arr->length) { panic(); } // Note: arr->length never changes
T object = arr->contents[<expression>]; // Oops.. <expression> gave a different value that is now out of bounds!

The problem is that relaxed atomics or volatile don't give much leeway to the optimizer. We'd like to let it reuse that value it already computed for index, as long as it doesn't decide to rematerialize it (which breaks the bounds check). For example, if you re-use the same index, such as in, say, the body of a C style or range-based for loop, you would really like the compiler to avoid re-loading that index value for every single generated index = <> expression when it could just use the first one.

Now I guess you could get away with something like "generate local variables as non-atomic; only use atomics for heap variables" but even then, if I do reference a heap variable multiple times I still want the compiler to keep it in a register as much as possible, which means it needs to be able to do that redundant load elimination.

In any case, my main point was to simply point out a case where you are definitely restricted to the C memory model, at least as far as the optimizer is concerned. Whether it is a significant restriction does not affect that it is a restriction.

2

u/kwan_e tonal-lang 16h ago

You could of course write your own optimizer to fix this problem but at that point, why even bother emitting C?

Because the "optimizer" can sit at the level of your HLL instead. Surely your HLL can detect when a variable is loaded from the same intended location, whether it is by variable name, or by index, and that they haven't been modified, by mutability checking.

eg, in your godbolt example, the result of the sum_unordered compilation is the same as if there were no atomics used. So the HLL would not need to bother emitting atomics in the first place, because the HLL already checked that the variables being referred to are the unchanged already, or indeed, prevented any modifying of the variables in the first place.

You would still emit C because it's easier to generate.

2

u/honey-pony 8h ago

I don't disagree that writing an optimizer is probably worth it (especially due to optimizations that can't be expressed in C or LLVM). Again, I'm mostly just responding to the claim that "[y]ou are not restricted to the C memory model." I don't think this is true. Writing workarounds to attempt to express an approximation of the semantics you want in C does not seem like you're actually breaking the limitations of its memory model.

As another example (although unrelated to the memory model), I don't think it is possible to express the semantic "null pointer deference is defined to be a segfault" if you're compiling to C (although tbf I also don't know if this is possible in LLVM). You can insert null pointer checks that call a panic() function, but there's no way to force the C compiler to treat null pointer loads as a deterministic pointer load (that will happen to be a segfault for 0 page pointers). If the C compiler ever works out that a pointer you're loading this way happens to be NULL, it's allowed to treat that as undefined behavior.

1

u/WittyStick 13h ago edited 12h ago

It's also only an optimization. If you change -O3 to -O0, you get:

sum_unordered:
    mov     rax, qword ptr [rdi]
    add     rax, qword ptr [rdi]
    ret

So it obviously doesn't provide a guarantee that it will not reload.

If qword ptr [rdi] were some volatile value/expression where reloading could give a different result, the compiler might know it cannot reload the value - however, that doesn't necessarily mean it won't have a redundant load. Consider it could emit something like the following:

sum_unordered:
    mov     rax, qword ptr [rdi]
    mov     qword ptr [rsp-8], rax
    mov     rax, qword ptr [rsp-8]
    add     rax, qword ptr [rsp-8]
    ret

First line reads the value once, second line stores that value on the stack. The last two lines reload the cached value off the stack. We still have a redundant load.

Obviously, this is unlikely to occur in this trivial example with optimizations turned on, but in more complex code other optimizations could interfere with it - the register allocator in particular. If you have a loop body with a lot of register pressure, the compiler might decide "actually, I don't need this index for a while - I'll stick it on the stack for now so I can use rax".

In the bounds checking example, we can insert a no-op with a memory clobber which would prevent the compiler from attempting to do T object = arr->contents[<expression>]; - it would know that it must use the index which was previously assigned.

uint64_t index = <expression>;
__asm__ volatile ("":::"memory");
if (index >= arr->length) { panic(); }
T object = arr->contents[index];

But this doesn't prevent the compiler doing the above - it could spill index onto the stack temporarily and reload that value later.

The method for avoiding this in C is to clobber a register for the index.

register uint64_t index __asm__("rax") = <expression>;
__asm__ volatile ("":::"memory");

Now you've told the compiler: "Please don't spill this register - keep index in it". There are obviously cases where this might not hold - such as if there's a call to a non-inline function further down the line - but if it does need to load it again, it's going to push the index it read first time onto the stack (or move it to a callee-saved register), and reload that same value back into rax after the call.

1

u/honey-pony 8h ago

It's also only an optimization.

This is kind of my point. I am talking about communicating the language semantics as accurately as possible to the lower level optimizer. C doesn't really give you the tools to do this. LLVM is (was?) very C++ brained so might also lean too closely to its semantics, but there are at least more tools than you have in C.

we can insert a no-op with a memory clobber

Unfortunately such a memory clobber does not actually help in the case of a dumb frontend (which is the case for my own project, currently). Because, of course, the memory clobber indicates that the index value could have changed, and so the compiler can't re-use the temporary generated for it. https://godbolt.org/z/dfW51vY8c

Now after all this discussion I do think I should probably implement some more optimizations in my own frontend or middle end or something. It should be possible for an expression like arr[idx] += 5 to only generate one bounds check, at the minimum. And I actually do think one relevant thing to do for my compiler (either in C or LLVM) would be to treat all stack-local variables as non-atomic (e.g. the index in a for loop); this would help a lot and wouldn't be super complicated to implement. (Although right now it just treats all variables as non-atomic and probably miscompiles something, lol).

But I can't say I've found C to be a particularly good backend target in terms of how easy it is to express specific semantics.

1

u/Norphesius 21h ago

You're restricted to a stack-vs-heap dichotomy, though practically for most languages outside of esoteric ones that doesn't matter too much. You can also simulate whatever weird memory model you want that doesn't have a stack, but at that point you have more of a VM written in C than a compilation target.

The practical issue is interfacing with the standard library. You can totally generate C code that is stdlib free, but then you're leaving a massive advantage of compiling to C on the table. Once you start relying on something like glibc, the abstractions start to leak out into your language if it doesn't align with C's design.

1

u/kwan_e tonal-lang 21h ago

> You're restricted to a stack-vs-heap dichotomy

No you're not. Why would you be?

People write C code that calls out to GPU, even before the days of shaders. The major C compilers give you intrinsics to call out to SIMD instructions. They have OpenMP support, if they would prefer that. If you don't want a "heap" but instead an "arena", you can implement in the high level language. Or you can implement in C and generate calls to it, because the high level language implemented on top handles the other stuff.

> but at that point you have more of a VM written in C than a compilation target.

When people say to use C as a "compilation target", they actually do just mean to use it as in intermediate language. So yes, you would expect them to implement a "VM" of sorts in which to implement the parts of the language at a higher level than C. That's what this is all about.

Even C++ originally started out as Cfront, which tried to generate everything via macros. Even C++ exceptions basically call out to C code in libunwind, despite it not looking like a library call.

There's nothing magic about compiling to C. You are adding a whole bunch of constraints to your thinking that doesn't need to be there.

> the abstractions start to leak out into your language if it doesn't align with C's design.

C is famous for its lack of abstractions. Literally have to do everything yourself. If you want the automatic stuff, you would implement in the high level language and generate the C calls.

Anything else that C would "leak" into your language is the OS stuff, and other interop stuff, which would also leak into your language if you generated assembly. You didn't escape those just because you use assembly.

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/chkno 18h ago edited 18h ago

You can implement unbounded tail recursion at a modest performance cost either with trampolines (the normal way) or with continuation passing and garbage-collecting stack frames (which is kind of crazy, but this is how Chicken Scheme does it!).

1

u/mamcx 20h ago

Another simpler option is compiling to web assembly.

1

u/DTCreeperMCL6 19h ago

I dont know anything about web assembly. What are the advantages to compiling to it and what is it for?

2

u/AverageHot2647 8h ago

It’s an instruction set for a virtual machine. In that way, it’s similar to Java byte code.

The main advantage of compiling to it is that it’s portable; WASM can run on any machine with a WASM runtime. It’s also the only programming language that runs in browsers other than JavaScript, so compiling to WASM allows you to target browsers.

It’s a similar set of tradeoffs to having your language target the JVM; like Clojure or Kotlin.

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.

1

u/perlgeek 9h ago

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.

To expand on that a bit: for language with Continuation-Passing Style, C is often a poor fit.

The other thing that is sometimes hard to integrate when compiling to C is nontrivial exception handling. C doesn't really have exceptions, so you have to fiddle with longjumps and manual stack unwinds, for example.

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:

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.

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:

  • 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/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).