[clang] [Clang][Driver] Preserve user --as-needed state around libgcc_s (PR #233236)

Wesley Lewis via cfe-commits cfe-commits at lists.llvm.org
Sun Oct 18 07:20:57 PDT 2026


wesley-lewis wrote:

I did the following tests with clang and GNU ld:

```
➜  tests ../llvm-project/build/bin/clang -shared -fPIC -Wl,--as-needed clang-link.c -o clang.so -###
clang version 24.0.0git (git at github.com:wesley-lewis/llvm-project.git fe04b9b583adcf40c44c3f525682ec28af4509ae)
Target: x86_64-unknown-linux-gnu
...
"-L/lib" "-L/usr/lib" "--as-needed" "/tmp/clang-link-8693c9.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "/usr/lib/gcc/x86_64-linux-gnu/15/crtendS.o" "/lib/x86_64-linux-gnu/crtn.o"
```

clang @fe04b9b

This is what gcc's output looks like: 

```
-L/lib -L/usr/lib --as-needed /tmp/ccEtaELW.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/15/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/15/../../../x86_64-linux-gnu/crtn.o
```

gcc at 15.2.0

### Solution I used: 

gcc uses --push-state and --pop-state to preserve the --as-needed. I made the changes to the driver based on this. 

### New output of clang based on the [changes](https://github.com/wesley-lewis/llvm-project/tree/clang-link-as-needed): 

```
➜  tests ../llvm-project/build/bin/clang -shared -fPIC -Wl,--as-needed clang-link.c -o clang.so -###
clang version 24.0.0git (git at github.com:wesley-lewis/llvm-project.git 39a563831fd3ee28aa78add07e7c384a74620c64)
Target: x86_64-unknown-linux-gnu
...
"-L/lib" "-L/usr/lib" "--as-needed" "/tmp/clang-link-b8cf23.o" "-lgcc" "--push-state" "--as-needed" "-lgcc_s" "--pop-state" "-lc" "-lgcc" "--push-state" "--as-needed" "-lgcc_s" "--pop-state" "/usr/lib/gcc/x86_64-linux-gnu/15/crtendS.o" "/lib/x86_64-linux-gnu/crtn.o"
```

### ELF output: 

#### Previously:

```
➜  tests readelf -d clang.so | grep NEEDED
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
```

#### After:

```➜  tests readelf -d clang.so | grep NEEDED```

returns nothing

https://github.com/llvm/llvm-project/pull/233236


More information about the cfe-commits mailing list