Skip to content

Commit 7ce5bb7

Browse files
committed
[Clang] Make '-Wglobal-constructors` work on the GNU attributes
Summary: The `-Wglobal-constructors` option is useful for restricting the usage of global constructors / destructors. However, it currently ignores the attributes that introduce global constructors, meaning that the module can still have ctors if `-Werror` is set. If this is intentional by the user, I believe it would be more correct to push the diagnostic.
1 parent 32f5437 commit 7ce5bb7

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7727,6 +7727,17 @@ void Sema::ProcessDeclAttributeList(
77277727
D->setInvalidDecl();
77287728
}
77297729

7730+
// Warn on global constructors and destructors created by attributes.
7731+
if (D->hasAttr<ConstructorAttr>() &&
7732+
!getDiagnostics().isIgnored(diag::warn_global_constructor,
7733+
D->getLocation()))
7734+
Diag(D->getLocation(), diag::warn_global_constructor)
7735+
<< D->getSourceRange();
7736+
if (D->hasAttr<DestructorAttr>() &&
7737+
!getDiagnostics().isIgnored(diag::warn_global_destructor,
7738+
D->getLocation()))
7739+
Diag(D->getLocation(), diag::warn_global_destructor) << D->getSourceRange();
7740+
77307741
// Do this check after processing D's attributes because the attribute
77317742
// objc_method_family can change whether the given method is in the init
77327743
// family, and it can be applied after objc_designated_initializer. This is a

clang/test/SemaCXX/attr-require-constant-initialization.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,11 @@ constexpr TestCtor<NotC> inval_constexpr(42); // expected-error {{must be initia
337337
ATTR constexpr TestCtor<NotC> inval_constexpr2(42); // expected-error {{must be initialized by a constant expression}}
338338
// expected-note@-1 {{in call to 'TestCtor(42)'}}
339339

340+
[[gnu::constructor]] void ctor() {}
341+
// expected-warning@-1 {{declaration requires a global constructor}}
342+
[[gnu::destructor]] void dtor() {}
343+
// expected-warning@-1 {{declaration requires a global destructor}}
344+
340345
#elif defined(TEST_THREE)
341346
#if defined(__cplusplus)
342347
#error This test requires C

0 commit comments

Comments
 (0)