kernel: Add C++ main() support

The C++ standard requires the main() function to have the return type
of 'int' and does not allow the main() to be defined with the 'void'
return type. Moreover, GCC goes as far as to emit a hard error when the
'::main()' has the return type of `void`.

This commit introduces an option to instruct the Zephyr kernel to call
the 'int main(void)' instead of the 'void main(void)' in case a Zephyr
application defines main() in a C++ source file.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
This commit is contained in:
Stephanos Ioannidis 2022-11-05 00:22:25 +09:00 committed by Stephanos Ioannidis
commit fa5fd41b61
3 changed files with 24 additions and 1 deletions

View file

@ -321,9 +321,13 @@ static void bg_thread_main(void *unused1, void *unused2, void *unused3)
z_mem_manage_boot_finish(); z_mem_manage_boot_finish();
#endif /* CONFIG_MMU */ #endif /* CONFIG_MMU */
#ifdef CONFIG_CPP_MAIN
extern int main(void);
#else
extern void main(void); extern void main(void);
#endif
main(); (void)main();
/* Mark nonessential since main() has no more work to do */ /* Mark nonessential since main() has no more work to do */
z_main_thread.base.user_options &= ~K_ESSENTIAL; z_main_thread.base.user_options &= ~K_ESSENTIAL;

View file

@ -21,8 +21,16 @@
#include <kernel_internal.h> #include <kernel_internal.h>
#ifdef CONFIG_CPP_MAIN
int __weak main(void)
#else
void __weak main(void) void __weak main(void)
#endif
{ {
/* NOP default main() if the application does not provide one. */ /* NOP default main() if the application does not provide one. */
arch_nop(); arch_nop();
#ifdef CONFIG_CPP_MAIN
return 0;
#endif
} }

View file

@ -54,6 +54,17 @@ config STD_CPP2B
endchoice endchoice
config CPP_MAIN
bool "C++ main() function definition"
help
This option instructs the Zephyr kernel to call the 'int main(void)'
instead of the 'void main(void)', which is the default main() type
for Zephyr.
C++ does not allow the main() to be defined with 'void' return type,
and any applications defining its main() in a C++ source file must
enable this option.
config LIB_CPLUSPLUS config LIB_CPLUSPLUS
bool "Link with STD C++ library" bool "Link with STD C++ library"
depends on !MINIMAL_LIBC depends on !MINIMAL_LIBC