简体   繁体   中英

Is it considered normal that -nostdlib does not prevent GCC/Clang to generate calls to C standard library functions?

From man gcc :

-nostdlib
  Do not use the standard system startup files or libraries when linking.

Here we see "when linking". Meaning that -nostdlib does not prevent GCC to generate calls to C standard library functions.

Let's check:

$ cat t35.c
#define SIZE 4096
char b[SIZE];
void _start(void)
{
  char *p = b;
  int i = SIZE;
  while(i > 0)
  {
    *p = 12;
    ++p;
    --i;
  }
}

$ arm-none-eabi-gcc t35.c -nostdlib -O2
ld.exe: cco83lvm.o: in function `_start':
t35.c:(.text+0x10): undefined reference to `memset'

Here we see that ld requires memset (because GCC generated memset ). Hence, the user needs to provide memset despite the fact that there is no memset in the user's program. For the user it may be confusing.

The same story for Clang: https://godbolt.org/z/jEz77fnf3 .

The overall question is simple: is it considered normal that -nostdlib does not prevent GCC/Clang to generate calls to C standard library functions?\


UPD. To prevent generation of certain C standard library functions there is a -ffreestanding option:

Assert that compilation targets a freestanding environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program startup may not necessarily be at "main". The most obvious example is an OS kernel. This is equivalent to -fno-hosted.

Demo:

$ arm-none-eabi-gcc t35.c -nostdlib -O2 -ffreestanding
<nothing> (expected)

Is it considered normal that -nostdlib does not prevent GCC/Clang to generate calls to C standard library functions?

Yes. The option is about linking and startup files, not about optimizations. When you use -nostdlib , you typically provide and link with your own implementation of memset .

Yes, this is documented. memset and a few others are a special case.

https://gcc.gnu.org/onlinedocs/gcc-12.2.0/gcc/Standards.html#Standards

Most of the compiler support routines used by GCC are present in libgcc, but there are a few exceptions. GCC requires the freestanding environment provide memcpy , memmove , memset and memcmp . Finally, if __builtin_trap is used, and the target does not implement the trap pattern, then GCC emits a call to abort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM