Skip to content

Commit d3584b4

Browse files
ajordanr-googledkalowsk
authored andcommitted
misc: Restrict linkage for main to freestanding
`extern "C"` is not a valid language linkage for declaring `int main(...)`, as per the ISO C++ Standard Specification. This fixes the violations of -Wmain, and brings Zephyr closer to valid C++. See the C++ standard wording here: https://eel.is/c++draft/basic.start.main#3.sentence-5 See also the clang warning -Wmain: https://clang.llvm.org/docs/DiagnosticsReference.html#wmain However, for freestanding code (i.e. with -ffreestanding), main has no special meaning, and we need to prevent name mangling. So allow this forward linkage when not hosted. This only applies to C++ as these linkage declarations only exist inside __cplusplus guards. Signed-off-by: Jordan R Abrahams-Whitehead <ajordanr@google.com>
1 parent 26a2478 commit d3584b4

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

include/zephyr/types.h

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,26 @@ typedef union {
4848
#endif /* Z_THREAD_LOCAL */
4949

5050
#ifdef __cplusplus
51-
/* Zephyr requires an int main(void) signature with C linkage for the application main if present */
51+
52+
#if (!__STDC_HOSTED__)
53+
/*
54+
* Zephyr requires an int main(void) signature with C linkage for the
55+
* application main if present. gcc, and clang when building in 'hosted' mode
56+
* will correctly assume this. But, when building freestanding, clang does not
57+
* treat main() specially, and by default name mangles its symbol, which
58+
* results in the linker not linking from the kernel init code into this
59+
* name mangled app main().
60+
*
61+
* At the same time, according to the C++ standard Section 6.9.3.1 of
62+
* ISO/IEC 14882:2024, main cannot be explicitly declared to have "C" linkage.
63+
* This restriction is relaxed for freestanding code, as main is not treated
64+
* specially in these circumstances.
65+
* Therefore, let's include the prototype when we are not building the code as
66+
* freestanding/not-hosted.
67+
*/
5268
extern int main(void);
5369
#endif
5470

55-
#ifdef __cplusplus
5671
}
5772
#endif
5873

0 commit comments

Comments
 (0)