jart / cosmopolitan

build-once run-anywhere c library
ISC License
18.08k stars 619 forks source link

Document appropriate compiler flags for clang usage #673

Open brenhinkeller opened 1 year ago

brenhinkeller commented 1 year ago

Hi folks. Awesome project! I was wondering if it might be possible to document somewhere an example of the clang equivalent to the simple gcc example given in the readme, i.e.:

wget https://justine.lol/cosmopolitan/cosmopolitan-amalgamation-2.1.1.zip
unzip cosmopolitan-amalgamation-2.1.1.zip
printf 'main() { printf("hello world\\n"); }\n' >hello.c
gcc -g -Os -static -nostdlib -nostdinc -fno-pie -no-pie -mno-red-zone \
  -fno-omit-frame-pointer -pg -mnop-mcount -mno-tls-direct-seg-refs -gdwarf-4 \
  -o hello.com.dbg hello.c -fuse-ld=bfd -Wl,-T,ape.lds -Wl,--gc-sections \
  -include cosmopolitan.h crt.o ape-no-modify-self.o cosmopolitan.a
objcopy -S -O binary hello.com.dbg hello.com

I understand that clang should in principle be an option here, but if I just try to substitute clang in for gcc here, I get various errors about unsupported flags, including

clang: error: unsupported option '-mnop-mcount' for target 'x86_64-pc-linux-gnu'

What would I have to change to get this to work with clang instead?

mulle-nat commented 1 year ago

The -pg and -mnop-mcount are for profiling, so they can be left out. I am using the following flags with my clang (variant). They are basically the same as the ones given for gcc separated, to build .o files and link them separately and DEPENDENCY_DIR is were I installed cosmopolitan into:

# nostdlib is not just a linker flag!
COSMOPOLITAN_CFLAGS="\
-static \
-nostdinc \
-nostdlib \
-D__STDC_NO_THREADS__ \
-isysroot '${DEPENDENCY_DIR}' \
-fno-omit-frame-pointer \
-fno-pie \
-gdwarf-4 \
-mno-red-zone \
-mno-tls-direct-seg-refs"

COSMOPOLITAN_LDFLAGS="\
-fuse-ld=bfd \
-gdwarf-4 \
-no-pie \
-nostdlib \
-Wl,-T,'${DEPENDENCY_DIR}/lib/ape.lds' \
-Wl,--gc-sections"

COSMOPOLITAN_OBJECTS="\
-Wl,'${DEPENDENCY_DIR}/lib/crt.o' \
-Wl,'${DEPENDENCY_DIR}/lib/ape-no-modify-self.o' \
-Wl,'${DEPENDENCY_DIR}/lib/cosmopolitan.a'"