如果至少没有使用-O2,则clang链接器会失败
我在一个简单的C代码中有一个strage行为,我正在为教育目的而做。
如果我使用低于-O2的值编译它,它会在链接版本中使用此输出中断。
$ make clang -Wall -march=native -pipe -c -g -D_DEBUG_ main.c clang -Wall -march=native -pipe -c -g -D_DEBUG_ functions.c clang -Wall -o main main.o functions.o Undefined symbols for architecture x86_64: "_getbit", referenced from: _getValueFromMatrix in functions.o "_setbit", referenced from: _populateMatrix in functions.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [main] Error 1
我不知道这是否有帮助,但这里是setbit()的实现; 和getbit();
inline void setbit(uint64_t *inteiro, unsigned char pos) { *(uint64_t*)inteiro |= (uint64_t)1 << pos; } inline bool getbit(uint64_t inteiro, unsigned char pos) { return (inteiro & ((uint64_t)1 << pos)); }
编辑:
functions.h
#ifndef __FUNCTIONS_H__ #define __FUNCTIONS_H__ /* Funções para manipulação de bits */ inline void setbit(uint64_t *, unsigned char); inline void clearbit(uint64_t *, unsigned char); inline bool getbit(uint64_t, unsigned char); inline unsigned char getbitChar(uint64_t, unsigned char); char *uint64_t2bin(uint64_t, char *, int); #endif
包含在main.c中
#include #include #include #include #include #include "errors.h" #include "const.h" #include "types.h" #include "functions.h"
如果.h文件中有函数的定义,则仅使用inline
是正确的。 它基本上告诉编译器它不应该为每个编译单元(你的.c文件)中的函数生成代码。
如果.h文件中没有这样的定义,就像在这里看到的那样,根本就不要使用inline
,它就没有意义了。
如果您担心的是定义inline
函数的单元中其他函数的效率,那么您实际上并不需要它。 编译器将内联它所掌握的任何函数,并且其标准表明它值得这样做。
如果您确实希望将定义放在头文件中,以便所有单元都能看到定义, 那么请使用inline
。 在这种情况下,您必须在一个单元中包含函数的“实例化”,以确保代码只发出一次:
extern inline void setbit(uint64_t *, unsigned char); extern inline void clearbit(uint64_t *, unsigned char); extern inline bool getbit(uint64_t, unsigned char); extern inline unsigned char getbitChar(uint64_t, unsigned char);
内联函数没有任何外部定义,因此当编译器无法内联它们(它不会在-O0
处进行内联)时,链接器无法找到定义,并且会产生错误。 最简单的解决方法是将inline
更改为static inline
。 非静态内联很难使用,令人困惑,而且通常没用。