我在 linux 内核中查看这个头文件: https://elixir.bootlin.com/linux/v4.14/source/arch/x86/boot/string.h
#ifndef BOOT_STRING_H
#define BOOT_STRING_H
/* Undef any of these macros coming from string_32.h. */
#undef memcpy
#undef memset
#undef memcmp
void *memcpy(void *dst, const void *src, size_t len);
void *memset(void *dst, int c, size_t len);
int memcmp(const void *s1, const void *s2, size_t len);
#define memcpy(d,s,l) __builtin_memcpy(d,s,l)
#define memset(d,c,l) __builtin_memset(d,c,l)
#define memcmp __builtin_memcmp
...
#endif /* BOOT_STRING_H */
我无法弄清楚 #undef + 函数声明 + 宏定义在 memcpy、memset 和 memcmp 上有什么作用。比如先声明一个函数memcpy,然后再定义一个宏memcpy。我不确定这样做的目的是什么。我发现这个函数在这里定义:https://elixir.bootlin.com/linux/v4.14/source/arch/x86/boot/copy.S#L20 .如果代码中某处使用 memcpy(例如此处:https://elixir.bootlin.com/linux/v4.14/source/arch/x86/boot/main.c#L40)使用 memcpy 它使用什么? copy.S 或 __builtin_memcpy 中定义的函数?
最佳答案
函数声明和宏没有冲突。 memcpy()
在内核中有几个定义,#undef
block 上方的注释暗示了这一点——还有另一个 memcpy()
在 string_32.h 中定义.
#undef memcpy
正在取消在 string_32.h 中找到的 #define
,这样它就不会存在于包含 < em>/boot/string.h。然后声明 memcpy()
,并为其构建一个新的宏。
#define
语句正在为 memcpy()
创建一个新宏,因为来自 string_32.h 的宏不再存在于此语境。内核开发人员出于各种原因使用宏。查看 this thread 中的答案了解更多。
/boot/copy.S 是一个 assembly file .您可以了解一下它的作用 here . /boot/main.c 中使用的 memcpy()
来自 /boot/string.h -- 检查 include 语句。
关于冲突的函数声明和宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797942/