我有一个在 code.h
中声明并在 code.c
中实现的函数。
它是这样的:
void someFunc(const char*);
和
#include "code.h"
void someFunc(const char* str){ printf("%s\n", str); }
现在我发现我可以删除任何一个文件中的const
(将其保留在另一个文件中),并且它编译和运行时没有错误。
我想知道这是什么意思?
其中一个文件是唯一重要的吗?
这听起来可能只是一个不重要的利基行为,但这一事实意味着错过的 const
可能会被忽视。
最佳答案
What happens if declaration and definition of a function don't agree on whether an argument is
const
or not?
您应该得到一个编译错误。
What to do?
更新您的编译器。
<小时/>使用 gcc 4.2.1,如果我从 header 或源文件中删除 const
,我会收到错误:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c code.c
code.c:3:6: error: conflicting types for 'someFunc'
void someFunc(const char* str){ printf("%s\n", str); }
^
./code.h:1:6: note: previous declaration is here
void someFunc(char*);
^
1 error generated.
使用 gcc 版本 4.9.2 (Debian 4.9.2-10),我得到了相同的行为。
与 gcc 7.1.0 版本相同的行为,在线 Wandbox :
我的猜测是,您所经历的行为取决于体系结构/编译器的版本。
关于C 函数中的 Const 声明和实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157072/