I have some very basic C code for which I want to view the equivalent assembly instructions. I'm interested to use zig cc
because it can cross compile to M1 ARM, X86, etc. Here is my code:
void variable_sort_2(int length, int *a) {
if(length == 2){
if(a[0] > a[1]){
int temp = a[0];
a[0] = a[1];
a[1] = temp;
}
}
}
static int a0[] = {};
int main(void){
variable_sort_2(0, a0);
return 0;
}
This will successfully do what I want using gcc
:
gcc -S sort2.c -o sort2.s
According to gcc --help
that will "Only run preprocess and compilation steps."
How to do the equivalent with zig cc
?
I tried doing the same -S
operation with zig cc
but it gives me a much larger output file:
$ zig cc -S sort2.c -o sort2.zig_cc.s
$ gcc -S sort2.c -o sort2.gcc.s
$ ls -l sort2*
-rw-r--r-- 1 mee wheel 236 Jun 13 12:32 sort2.c
-rw-r--r-- 1 mee wheel 27646 Jun 13 16:32 sort2.zig_cc.s
-rw-r--r-- 1 mee wheel 1455 Jun 13 16:33 sort2.gcc.s
$ wc -l *s
63 sort2.gcc.s
688 sort2.zig_cc.s
I don't understand assembly well enough to explain why the zig cc
file is ten times longer; my assumption is it's linking in system stuff, but I don't know. I see lots of lines like this:
.byte 17 ## DW_TAG_compile_unit
.byte 1 ## DW_CHILDREN_yes
.byte 37 ## DW_AT_producer
.byte 14 ## DW_FORM_strp
.byte 19 ## DW_AT_language
.byte 5 ## DW_FORM_data2
That's lines 300 through 305 of the zig cc -S
compiled output on my computer:
$ uname -a
Darwin meee 22.2.0 Darwin Kernel Version 22.2.0: Fri Nov 11 02:08:47 PST 2022; root:xnu-8792.61.2~4/RELEASE_X86_64 x86_64
I created 3 github gists to contain the C code and the two assembly files: sort2.c, sort2.zig_cc.s, sort2.gcc.s:
- https://gist.github.com/purplejacket/4f5678f985e8a1154b3e9e3116ce6a64
- https://gist.github.com/purplejacket/5a12a602e7a26fbbcbd2493ef69d0a0b
- https://gist.github.com/purplejacket/65b63cb7ef81ae1ecb8413eb5903ea45
@ShadowRanger suggested trying -g0
which makes the file smaller, but still not as small as I get with gcc
.
$ zig cc -S -g0 sort2.c -o sort2.g0.s
$ ls -l sort2.g0.s
-rw-r--r-- 1 mee wheel 5042 Jun 14 17:40 sort2.g0.s
$ wc -l sort2.g0.s
239 sort2.g0.s
And here is a gist for that output file: