简体   繁体   English

C ++中的C ++名称

[英]C++ name mangling in C

C language does not use name mangling like C++. C语言不使用像C ++这样的名称修改。 This can lead to subtle bugs, when function prototype is declared differently in different files. 当函数原型在不同文件中声明不同时,这会导致细微的错误。 Simple example: 简单的例子:

/* 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;
}

When compiling such code using C compiler (in my case gcc) no errors are reported. 使用C编译器(在我的情况下为gcc)编译此类代码时,不会报告任何错误。 After switching to C++ compiler, linking will fail with error "undefined reference to 'test(int)'". 切换到C ++编译器后,链接将失败,并显示错误“未定义引用'test(int)'”。 Unfortunately in practice this is not so easy - there are cases when code is accepted by C compiler (with possible warning messages), but compilation fails when using C++ compiler. 不幸的是,在实践中这并不容易 - 有些情况下C编译器接受代码(带有可能的警告消息),但使用C ++编译器时编译失败。

This is of course bad coding practice - all function prototypes should be added to .h file, which is then included in files where function is implemented or used. 这当然是错误的编码实践 - 所有函数原型都应该添加到.h文件中,然后将其包含在实现或使用函数的文件中。 Unfortunately in my app there are many cases like this, and fixing all of them is not possible in short term. 不幸的是,在我的应用程序中有很多这样的情况,并且短期内无法修复所有这些情况。 Switching to g++ is also not at option, I got compilation error quite fast. 切换到g ++也不是选择,我很快就得到了编译错误。

One of possible solutions would be to use C++ name mangling when compiling C code. 一种可能的解决方案是在编译C代码时使用C ++名称修改。 Unfortunately gcc does not allow to do this - I did not found command line option to do this. 不幸的是,gcc不允许这样做 - 我没有找到命令行选项来执行此操作。 Do you know if it is possible to do this (maybe use other compiler?). 你知道是否可以这样做(也许使用其他编译器?)。 I also wonder if some static analysis tools are able to catch this. 我也想知道一些静态分析工具是否能够捕捉到这一点。

Using splint catches these kinds of errors. 使用splint捕获这些错误。

foo.c: foo.c的:

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

bar.c: bar.c:

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

Running splint : 运行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$ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM