]> git.ipfire.org Git - thirdparty/glibc.git/commitdiff
Use __builtin_FILE instead of __FILE__ in assert in C++.
authorPaul Pluzhnikov <ppluzhnikov@google.com>
Fri, 10 Feb 2023 16:14:30 +0000 (16:14 +0000)
committerPaul Pluzhnikov <ppluzhnikov@google.com>
Fri, 10 Feb 2023 17:12:40 +0000 (17:12 +0000)
Likewise use __builtin_LINE instead of __LINE__.

When building C++, inline functions are required to have the exact same
sequence of tokens in every translation unit. But __FILE__ token, when
used in a header file, does not necessarily expand to the exact same
string literal, and that may cause compilation failure when C++ modules
are being used. (It would also cause unpredictable output on assertion
failure at runtime, but this rarely matters in practice.)

For example, given the following sources:

  // a.h
  #include <assert.h>
  inline void fn () { assert (0); }

  // a.cc
  #include "a.h"

  // b.cc
  #include "foo/../a.h"

preprocessing a.cc will yield a call to __assert_fail("0", "a.h", ...)
but b.cc will yield __assert_fail("0", "foo/../a.h", ...)

assert/assert.h

index 72209bc5e747c6426db23c46f8f43894026a3c19..62670e4bbbb39bdc522c6fe2ad4ef6a67d3c5cad 100644 (file)
@@ -86,10 +86,21 @@ __END_DECLS
    parentheses around EXPR.  Otherwise, those added parentheses would
    suppress warnings we'd expect to be detected by gcc's -Wparentheses.  */
 # if defined __cplusplus
+#  if defined __has_builtin
+#   if __has_builtin (__builtin_FILE)
+#    define __ASSERT_FILE __builtin_FILE ()
+#    define __ASSERT_LINE __builtin_LINE ()
+#   endif
+#  endif
+#  if !defined __ASSERT_FILE
+#   define __ASSERT_FILE __FILE__
+#   define __ASSERT_LINE __LINE__
+#  endif
 #  define assert(expr)                                                 \
      (static_cast <bool> (expr)                                                \
       ? void (0)                                                       \
-      : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))
+      : __assert_fail (#expr, __ASSERT_FILE, __ASSERT_LINE,             \
+                       __ASSERT_FUNCTION))
 # elif !defined __GNUC__ || defined __STRICT_ANSI__
 #  define assert(expr)                                                 \
     ((expr)                                                            \