gpt4 book ai didi

c++ - 何时不将 C 函数原型(prototype)放在头文件中

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:06 25 4
gpt4 key购买 nike

为什么将 C/C++ 函数原型(prototype)放在头文件中而不是将它们放在主 .c/.cpp 文件的顶部可能不是好的做法?

例如,我可以编写一个 dothis.c 文件:

#include "funcs.h"

int main(int argc, char ** argv) {
// some code
int result = doThis();
// more code

return 0;
}

int doThis(void) {
// code and return value
}

在我的 funcs.h 文件中,我会写:

#ifndef FUNCS_H
#define FUNCS_H

int doThis(void);

// more function prototypes

#endif // FUNCS_H

有什么理由可以更好地将原型(prototype)(假设有很多)放在 .c/.cpp 文件的顶部?例如:

#include "funcs.h"

int doThis(void);

// more function prototypes

int main(int argc, char ** argv) {
// some code
int result = doThis();
// more code

return 0;
}

int doThis(void) {
// code and return value
}

在第一种情况下,我觉得将许多函数原型(prototype)放在一个单独的头文件和文档中以在逻辑上将声明与实现分开并更容易简明地查看主文件在做什么会很有帮助。

最佳答案

Is there a reason why it might not be good practice to place C/C++ function prototypes in header files but instead place them at the top of the main .c/.cpp file?

唯一对我有意义的是当函数是其他函数的实现细节时。当然,在那种情况下,我更喜欢使用文件作用域函数在文件作用域中定义它们,使用 static 限定符或将它们放在特定于 .cpp 文件的命名空间中。

对于所有其他函数,我发现很难证明不将声明放在头文件中并在使用函数的文件和定义函数的文件中#includeing 头文件功能。

关于c++ - 何时不将 C 函数原型(prototype)放在头文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com