我出于教育目的在简单的 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));
}
编辑:
函数.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 <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "errors.h"
#include "const.h"
#include "types.h"
#include "functions.h"
最佳答案
inline
只有在 .h 文件中有函数定义的情况下才是正确的使用方式。它基本上告诉编译器它不应该为每个编译单元(您的 .c 文件)中的函数生成代码。
如果 .h 文件中没有这样的定义,就像这里看起来的那样,根本就不要使用 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);
关于如果至少未使用 -O2,则 clang 链接器将失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939482/