Compiling c code into machine code using rust

i am making a compiler with rust, and compiling the code into c code. i want to compile the c code into machine code. my original plan was to find the current os, and what is the compiler it uses for c code. but i saw that there's crates that already do that for me. i tried using cc, but it compiles into a library, so there's no main and the program can't be compiled into an executable. so i came here to ask if there's any crates or ways to compile c code like with the crate cc, but to machine code.

Set the -shared flag. When enabled, the compiler will produce a shared object which can then be linked with other objects to form an executable.

Perhaps this might help. You'd have to invoke a linker yourself though.

that kind of ruins the point of cc. idk what kind of OS does the person compiling have, so i can't just call ld main.o and pray it works. also, i tested it out, and cc does work fine if you just remove the "-c" line from the command running the code. idk how to remove that flag though

You can use cc main.o -o main, right? That should work on any UNIX afaik and for windows you can invoke link.exe instead.

the stated goal of the cc crate is:

This library is intended to be used as a build-dependencies entry in Cargo.toml:
The purpose of this crate is to provide the utility functions necessary to compile C code into a static archive which is then linked into a Rust crate.

so the Build type has APIs like get_compiler(), get_archiver() and get_ranlib(), but there's no get_linker().

using get_compiler(), you can get the path of the compiler, I think you may be able to use the compiler as your linker, you just need to figure out what system libraries you need to link, and it depends on how you generated the C code. see:

another approach is not to detect the system C toolchain, but bundle your own compiler and linker, zig is a good choice, and it also can do cross compiling. see also:

i cloned the git repo and saw that all i had to do was to remove the "-I" from the command running, and the code would work. to anyone who wants to replicate this, clone the cc repo, go to src/, find every instance of cmd.arg("-I").arg(&**directory); and remove it. that alone would work, but there would still remain some extra things like a static link library and some extra compilation data

oh, i entirely missed this post. i already found an answer, but yours might be better. btw, i was not looking for the compiler, but for running the command cc main.c. cc doesn't just compile your code into a linked library, it also checks every flag you send it and transfers it into into the right flag for the existing compiler.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.