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

YunQiang Su via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 16 23:49:10 PST 2025


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

>From cc30e98287ec0ceca490f1f6a16a0190ff243ed6 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 | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Headers/limits.h b/clang/lib/Headers/limits.h
index d08227fe4d3d48..f5f8dd5559d20a 100644
--- a/clang/lib/Headers/limits.h
+++ b/clang/lib/Headers/limits.h
@@ -20,8 +20,10 @@
 #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. If we are included by libc with include_next,
+   we shouldn't include it again. */
+#if __STDC_HOSTED__ &&                                                         \
+    __has_include_next(<limits.h>) && !defined(_LIBC_LIMITS_H_) && !defined(_LIMITS_H)
 #include_next <limits.h>
 #endif
 



More information about the cfe-commits mailing list