Author: Fangrui Song
Date: 2026-11-28T11:33:00-08:00
New Revision: d03d79ae705ba99a22b0304144a3c3da21a05c60

URL: 
https://github.com/llvm/llvm-project/commit/d03d79ae705ba99a22b0304144a3c3da21a05c60
DIFF: 
https://github.com/llvm/llvm-project/commit/d03d79ae705ba99a22b0304144a3c3da21a05c60.diff

LOG: [CMake] Enable -Werror=global-constructors for clang/lib (#246753)

Like #239678, enforce
llvm.org/docs/CodingStandards.html#do-not-use-static-constructors in
Clang builds for clang/lib source files.

List the libraries that still have C++ dynamic initializations so that
the others cannot gain new ones.

Examples: Remove cl::opt, make the constructor `constexpr` (#223903),
move globals with ctor/dtor out of headers, or into a function-local
static (#234442)

LLM-aided

Added: 
    

Modified: 
    clang/lib/CMakeLists.txt

Removed: 
    


################################################################################
diff  --git a/clang/lib/CMakeLists.txt b/clang/lib/CMakeLists.txt
index 22d260e55b271..3aee16eea4feb 100644
--- a/clang/lib/CMakeLists.txt
+++ b/clang/lib/CMakeLists.txt
@@ -1,3 +1,11 @@
+# HAS_WERROR_GLOBAL_CTORS and LLVM_HAS_NOGLOBAL_CTOR_MUTEX are cached by
+# llvm/lib/Support/CMakeLists.txt. They are unset in a standalone build, which
+# skips the check.
+if (HAS_WERROR_GLOBAL_CTORS AND LLVM_HAS_NOGLOBAL_CTOR_MUTEX)
+  set(CLANG_LIB_WERROR_GLOBAL_CTORS ON)
+  string(APPEND CMAKE_CXX_FLAGS " -Werror=global-constructors")
+endif()
+
 add_subdirectory(Headers)
 add_subdirectory(Basic)
 add_subdirectory(APINotes)
@@ -37,3 +45,33 @@ add_subdirectory(UnifiedSymbolResolution)
 if(CLANG_ENABLE_CIR)
   add_subdirectory(CIR)
 endif()
+
+# Libraries that still have static initializers. Remove a library once it has
+# none, so that it cannot regain them.
+if (CLANG_LIB_WERROR_GLOBAL_CTORS)
+  foreach(lib
+      SSAFExamplePlugin
+      clangBasic
+      clangDriver
+      clangFormat
+      clangFrontendTool
+      clangInstallAPI
+      clangInterpreter
+      clangScalableStaticAnalysisAnalyses
+      clangScalableStaticAnalysisCore
+      clangScalableStaticAnalysisSourceTransformation
+      clangSema
+      clangSerialization
+      clangStaticAnalyzerCheckers
+      clangStaticAnalyzerCore
+      clangStaticAnalyzerFrontend
+      clangTooling
+      clangToolingInclusions
+      )
+    if (TARGET obj.${lib})
+      target_compile_options(obj.${lib} PRIVATE -Wno-global-constructors)
+    elseif (TARGET ${lib})
+      target_compile_options(${lib} PRIVATE -Wno-global-constructors)
+    endif()
+  endforeach()
+endif()


        
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to