[clang] clang/limits.h: Avoid including limits.h twice (PR #120526)

YunQiang Su via cfe-commits cfe-commits at lists.llvm.org
Wed Dec 18 22:22:17 PST 2024


https://github.com/wzssyqa created https://github.com/llvm/llvm-project/pull/120526

The limits.h of glibc, aka /usr/include/limits.h file of *-linux-gnu systems, has `#include_next <limits.h>`, so the limits.h from clang is included.

And in the limits.h for clang, `#include_next <limits.h>` is also used.

Normally it won't be a problem as the headers is protected by something like _LIBC_LIMITS_H_, while it may be a problem when we cross-build glibc on a none glibc platform. For example if we build glibc for x86_64-linux-gnu on a x86_64-linux-musl platform.

To test it, we can do
```
echo "#include </usr/include/limits.h>" | bin/clang -E -O2 -xc - -MM -H
```
We can see there is
```
. /usr/include/limits.h
.. /usr/lib/llvm-19/lib/clang/19/include/limits.h
... /usr/include/limits.h
```

>From a7e475b01b73c66965403330f6ad377b32e13e74 Mon Sep 17 00:00:00 2001
From: YunQiang Su <yunqiang at isrc.iscas.ac.cn>
Date: Thu, 19 Dec 2024 14:09:04 +0800
Subject: [PATCH] clang/limits.h: Avoid including limits.h twice

The limits.h of glibc, aka /usr/include/limits.h file of *-linux-gnu
systems, has `#include_next <limits.h>`, so the limits.h from clang
is included.

And in the limits.h for clang, `#include_next <limits.h>` is also
used.

Normally it won't be a problem as the headers is protected by something
like _LIBC_LIMITS_H_, while it may be a problem when we cross-build
glibc on a none glibc platform. For example if we build glibc for
x86_64-linux-gnu on a x86_64-linux-musl platform.

To test it, we can do
```
echo "#include </usr/include/limits.h>" | bin/clang -E -O2 -xc - -MM -H
```
We can see there is
```
. /usr/include/limits.h
.. /usr/lib/llvm-19/lib/clang/19/include/limits.h
... /usr/include/limits.h
```
---
 clang/lib/Headers/limits.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Headers/limits.h b/clang/lib/Headers/limits.h
index d08227fe4d3d48..90f01791f857ee 100644
--- a/clang/lib/Headers/limits.h
+++ b/clang/lib/Headers/limits.h
@@ -20,8 +20,9 @@
 #endif
 
 /* System headers include a number of constants from POSIX in <limits.h>.
-   Include it if we're hosted. */
-#if __STDC_HOSTED__ && __has_include_next(<limits.h>)
+   Include it if we're hosted. The limits.h of glibc uses include_next to
+   include us, we shouldn't include it again. */
+#if __STDC_HOSTED__ && __has_include_next(<limits.h>) && !defined(_LIBC_LIMITS_H_)
 #include_next <limits.h>
 #endif
 



More information about the cfe-commits mailing list