C中的c++名称混淆

C++ name mangling in C

本文关键字:中的 c++      更新时间:2023-10-16

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$