llvm / llvm/llvm-project

[libc] Request for Annex K via `__STDC_WANT_LIB_EXT1__` doesn't work as expected

Open
#195,276 2 comments 0 reactions 0 assignees View on GitHub
libc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Source code:
```c
#include
#define __STDC_WANT_LIB_EXT1__ 1
#include

int foo() {
return strnlen_s("abc", 2);
}
```
Compile with:
`clang -c a.c`

We get the error:
```
a.c:6:10: error: call to undeclared function 'strnlen_s'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
6 | return strnlen_s("abc", 2);
| ^
```

If we move the line `#define __STDC_WANT_LIB_EXT1__ 1` before `#include `, it works as expected.

**Analysis**

I believe this issue is caused by the header inclusion guard in `llvm-libc-macros/annex-k-macros.h`.

The inclusion of `stdio.h` implies a recursive inclusion of `annex-k-macros.h`. But at that point, the `__STDC_WANT_LIB_EXT1__` is not yet defined, therefore the macro who controls the availability of Annex K functionality, `LIBC_HAS_ANNEX_K`, is not defined.

By the time `__STDC_WANT_LIB_EXT1__` is defined and `string.h` is included, the recursive inclusion of `annex-k-macros.h` (by the second time now) is stopped at the header inclusion guard, hence `LIBC_HAS_ANNEX_K` is again not defined. As a result, the declaration of `strnlen_s` is never brought in.

Found by @simpal01

Contributor guide

Open the contributing guide

Research direction

Reproduce the include-order example with clang, then inspect llvm-libc-macros/annex-k-macros.h and the stdio.h and string.h inclusion paths. Trace when LIBC_HAS_ANNEX_K is defined; done means strnlen_s is declared when __STDC_WANT_LIB_EXT1__ is defined between the two includes, with a regression test covering that order.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
compilers, operating-systems
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.