strlen for string literal

Environment

Sample code

#include <string.h>

size_t string_const_size() {
    return strlen("hello world");
}

Compile with gcc -O0

gcc -O0 -c strlen.c
objdump -S strlen.o
strlen.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <string_const_size>:
   0:   f3 0f 1e fa             endbr64 
   4:   55                      push   %rbp
   5:   48 89 e5                mov    %rsp,%rbp
   8:   b8 0b 00 00 00          mov    $0xb,%eax ;; 0xb=11 is string length of "hello world"
   d:   5d                      pop    %rbp
   e:   c3                      retq   

strlen for string literal is calculated at compiling time even if optimization is disabled

Compile with clang -O0

I got same result as gcc

strlen.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <string_const_size>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   b8 0b 00 00 00          mov    $0xb,%eax ;; here
   9:   5d                      pop    %rbp
   a:   c3                      retq   
   b:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)

Compile with gcc -O0 -fno-builtin

It looks strlen is called

strlen.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <string_const_size>:
   0:   f3 0f 1e fa             endbr64 
   4:   55                      push   %rbp
   5:   48 89 e5                mov    %rsp,%rbp
   8:   48 8d 3d 00 00 00 00    lea    0x0(%rip),%rdi        # f <string_const_size+0xf>
   f:   e8 00 00 00 00          callq  14 <string_const_size+0x14>
  14:   5d                      pop    %rbp
  15:   c3                      retq   

Summary

I suppose I can use strlen for litaral string without runtime overhead and I don't need hack as below

const size_t some_length = sizeof("Hello World") -1;