简体   繁体   中英

How to compile C code on Linux/GCC without deprecated functions being available?

There are old functions such as index , rindex which have now been superseded by strchr and strrchr .

Is there a way to configure the compiler or defines so these functions aren't available?

It can cause confusing warnings when:

  • accidentally using index name outside of scope for eg - or worse, not warn and use the function in a way that's not intended.
  • Older GCC versions (4.x) warn when using -Wshadow if you have a variable called index .

See:


Notes:

  • as @antti-haapala says, the global symbol index shouldn't be redefined since libraries may use it.
    This question is regarding the common case when a local variable is called index .
  • At the time of writing, glibc doesn't mark these functions with the deprecated attribute, so warnings related to using deprecated functions have no effect.

Use the compiler in ISO C mode. The C standard prohibits conforming programs being broken by the presence of identifiers that are not reserved words.

For example, use flags -std=c99 .

Sample program:

#include <string.h>

int main()
{
   index("abc", 'x');
}

Compiled with -std=c11 -Werror gives:

error: implicit declaration of function 'index' [-Werror=implicit-function-declaration]

您不应该重新定义这些标识符,因为您链接的某些库仍然可能依赖于它们。

If I understand well, you want to use index as a variable name without conflicting with the index function included in <strings.h> .

In this case you can override using the preprocessor:

#include <stdio.h>
#define index(s, c) deprecated_index(s, c)
#include <strings.h>

int index = 5;

int main(void)
{
    printf("%d\n", index);
    return 0;
}

Or override index with strchr :

#include <stdio.h>
#include <string.h>
#include <strings.h>

#define index(s, c) strchr(s, c)

int main(void)
{
    int index = 5;
    char *ptr = index("text", 'x');

    printf("%s %d\n", ptr, index);
    return 0;
}

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