Why do you have to link the math library in C?

后端 未结 11 1090
难免孤独
难免孤独 2020-11-22 01:04

If I include or in a C program I don\'t have to link these when compiling but I do have to link to

11条回答
  •  死守一世寂寞
    2020-11-22 01:49

    Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

    An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

    Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

提交回复
热议问题