C中的c++名称混淆
C++ name mangling in C
C语言不像c++那样使用名称混淆。当函数原型在不同的文件中声明不同时,这可能会导致微妙的bug。简单的例子:
/* file1.c */
int test(int x, int y)
{
return y;
}
/* file2.c */
#include <stdio.h>
extern int test(int x);
int main()
{
int n = test(2);
printf("n = %dn", n);
return 0;
}
当使用C编译器(在我的情况下是gcc)编译这些代码时,没有错误报告。切换到c++编译器后,链接将失败,错误为"undefined reference to 'test(int)'"。不幸的是,在实践中,这并不是那么容易的-在某些情况下,代码被C编译器接受(可能带有警告消息),但在使用c++编译器时编译失败。
这当然是不好的编码实践——所有的函数原型都应该添加到。h文件中,然后包含在函数实现或使用的文件中。不幸的是,在我的应用程序中有很多这样的情况,修复所有这些是不可能在短期内。切换到g++也不是一个选项,我得到编译错误相当快。
一个可能的解决方案是在编译C代码时使用c++名称混淆。不幸的是,gcc不允许这样做——我没有找到这样做的命令行选项。你知道是否有可能做到这一点(也许使用其他编译器?)。我也想知道是否有一些静态分析工具能够捕捉到这个
使用splint
捕获这些类型的错误。
foo.c:
int test(int x);
int main() {
test(0);
}
bar.c:
int test(int x, int y) {
return y;
}
Running splint
:
$ splint -weak foo.c bar.c
Splint 3.1.2 --- 20 Feb 2009
bar.c:1:5: Function test redeclared with 2 args, previously declared with 1
Types are incompatible. (Use -type to inhibit warning)
foo.c:4:5: Previous declaration of test
Finished checking --- 1 code warning
~/dev/temp$ cat > a.c
int f(int x, int y) { return x + y; }
~/dev/temp$ cat > b.c
extern int f(int x); int g(int x) { return f(x + x); }
~/dev/temp$ splint *.c
Splint 3.1.2 --- 03 May 2009
b.c:1:12: Function f redeclared with 1 arg, previously declared with 2
Types are incompatible. (Use -type to inhibit warning)
a.c:1:5: Previous declaration of f
Finished checking --- 1 code warning
~/dev/temp$
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 内置函数可查看CPP中的成员变量