C ++中的C ++名称

时间:2014-07-30 18:24:13

标签: c++ c gcc name-mangling

C语言不使用像C ++这样的名称修改。当函数原型在不同文件中声明不同时,这会导致细微的错误。简单的例子:

/* 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 = %d\n", n);
    return 0;
}

使用C编译器(在我的情况下为gcc)编译此类代码时,不会报告任何错误。切换到C ++编译器后,链接将失败并出现错误&#34;未定义引用&#39; test(int)&#39;&#34;。不幸的是,在实践中这并不容易 - 有些情况下C编译器接受代码(带有可能的警告消息),但使用C ++编译器时编译失败。

这当然是错误的编码实践 - 所有函数原型都应该添加到.h文件中,然后将其包含在实现或使用函数的文件中。不幸的是,在我的应用程序中有很多这样的情况,并且短期内无法修复所有这些情况。切换到g ++也不是选择,我很快就得到了编译错误。

可能的解决方案之一是在编译C代码时使用C ++名称修改。不幸的是,gcc不允许这样做 - 我没有找到命令行选项来执行此操作。你知道是否可以这样做(也许使用其他编译器?)。我也想知道是否有一些静态分析工具可以解决这个问题。

2 个答案:

答案 0 :(得分:1)

使用splint可以捕获这些错误。

foo.c的:

int test(int x);
int main() {
    test(0);
}

bar.c:

int test(int x, int y) {
    return y;
}

正在运行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

答案 1 :(得分:0)

~/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$