user1273684
user1273684

Reputation: 1619

When is gcc evaluating functions at compile time?

When I have the following code

int main(void) {
        printf("%zd\n", strlen("Hello World!"));

        return 0;
}

and compile it with -O3, strings will show that the string "Hello World!" is missing from the binary since it got evaluated at compile time.

If I instead use my own function

static inline size_t my_strlen(const char *s) {
        const char *tmp = s;

        while (*++tmp);

        return tmp - s;
}

int main(void) {
        printf("%zd\n", my_strlen("Hello World!"));

        return 0;
}

with the same options, the string can still be found in the binary.

Why is this?

Upvotes: 2

Views: 2127

Answers (2)

Because it is an optimization permitted by the standard.

On some systems, strlen is finally expanded to _builtin_strlen which is known by the GCC compiler. On my machine /usr/include/x86_64-linux-gnu/bits/string.h (which is indirectly included by <string.h>) has

# define strlen(str) \
  (__extension__ (__builtin_constant_p (str)         \
                 ? __builtin_strlen (str)            \
                 : __strlen_g (str)))

So actually is it done by the mix of GNU glibc and gcc

Upvotes: 5

TheSuper
TheSuper

Reputation: 645

GCC probably has an optimization somewhere that replaces the strlen() of a constant string with the length of that string.

When you use your own function, this optimization cannot be turned on. GCC does not know if the my_strlen has side-effects, so it has to run it each time.

Upvotes: 2

Related Questions