在 header 中使用 ifdef linux 等有意义吗?
Does it make sense to use ifdef linux etc in header?
我读了一些关于使用 #ifdef #elif
etc 宏以提供各种平台实现的文章,几乎每个人都说应该尽可能避免,因为它很难维护。然而,我目前正在考虑它在 header 文件中的用法,如下所示:
#ifdef __linux__
typedef struct my_linux_struct my_struct
#elif __APPLE__
typedef struct my_macos_struct my_struct
#else
#error Platform not supported
#endif
尽管目的相同,但 struct my_linux_struct
和 struct my_macos_struct
的实现完全不同。
所以我为每个平台都有一个专用的 c
文件,其中定义了平台的结构(struct my_linux_struct
或 struct my_macos_struct
)。
我对结构进行不同命名的好处是避免了实现中的名称冲突。
这样写条件宏是一种常见的做法吗?或者我们应该尽可能避免写这样的东西。
Is it a common practice to write conditional macro like that? Or we should avoid writing such things whenever possible.
介于两者之间。
最好将差异放在 .c 文件中,但不要避免 "whenever possible"。
将特定于平台的代码保留在 .h 文件之外更好,但不是法律。
我读了一些关于使用 #ifdef #elif
etc 宏以提供各种平台实现的文章,几乎每个人都说应该尽可能避免,因为它很难维护。然而,我目前正在考虑它在 header 文件中的用法,如下所示:
#ifdef __linux__
typedef struct my_linux_struct my_struct
#elif __APPLE__
typedef struct my_macos_struct my_struct
#else
#error Platform not supported
#endif
尽管目的相同,但 struct my_linux_struct
和 struct my_macos_struct
的实现完全不同。
所以我为每个平台都有一个专用的 c
文件,其中定义了平台的结构(struct my_linux_struct
或 struct my_macos_struct
)。
我对结构进行不同命名的好处是避免了实现中的名称冲突。
这样写条件宏是一种常见的做法吗?或者我们应该尽可能避免写这样的东西。
Is it a common practice to write conditional macro like that? Or we should avoid writing such things whenever possible.
介于两者之间。
最好将差异放在 .c 文件中,但不要避免 "whenever possible"。
将特定于平台的代码保留在 .h 文件之外更好,但不是法律。