C 函数中的 Const 声明和实现

标签 c function compilation constants function-prototypes

我有一个在 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 : enter image description here

我的猜测是,您所经历的行为取决于体系结构/编译器的版本。

关于C 函数中的 Const 声明和实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157072/

相关文章:

C - 我认为我做错了 realloc

python - 有没有办法使矩形形状函数为正值?

c++ - 将参数添加到列表并在 C 预处理器宏中应用另一个宏

function -::(双冒号)代表什么?

Javascript 日期函数不起作用

c++ - 编译 wsdlpull

c++ - Codeblocks 编译,GCC 不编译

c - 应用程序二进制接口(interface)困惑

c - 循环数组,找到零,执行操作,停止

c - 匿名结构 + 复合文字导致 lint 错误