我期望用C ++编译器编译C代码有什么问题? [英] What issues can I expect compiling C code with a C++ compiler?

查看:183
本文介绍了我期望用C ++编译器编译C代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用现有的C代码库并使用C ++编译器编译它,您期望出现什么样的问题?例如,我认为将一个整数赋值给枚举类型的值在C ++中将失败,而在C中它是合法的(如果有点讨厌)。



如果我不要将所有我的C文件包装在 extern C {...} ,我要得到名称mangling在哪里我最不期望的?有什么原因我真的不应该这样做吗?



对于背景,我们有一个非常大的代码库用C编写。几年来,跳过了箍,做自然会通过C ++(例如homebrewe继承)的事情。我们想开始走向C ++,但是以渐进的方式;得到我们的CORBA类框架来支持它,并且重构模块,以便利用C ++提供的更自然的方法。

解决方案

我这样做过一次。问题的主要来源是C ++对类型更严格,正如你怀疑的。你必须添加转换,其中void *与其他类型的指针混合。喜欢分配内存:

  Foo * foo; 
foo = malloc(sizeof(* foo));以上是典型的C代码,但是需要在C ++中进行转换:



  Foo * foo; 
foo =(Foo *)malloc(sizeof(* foo));

在C ++中有新的保留字,如class,and,bool ,catch,delete,explicit,mutable,namespace,new,operator,or,private,protected,friend作为变量名。



上述可能是使用C ++编译器编译旧C代码时最常见的问题。有关不兼容的完整列表,请参见 ISO C和ISO C ++之间的不兼容性。 p>

你也问一下名字是什么。在没有externC包装器的情况下,C ++编译器将修改符号。这不是一个问题,只要你使用一个C ++编译器,并不依赖于dlsym()或类似的东西从库中拉符号。


If you take an existing C code base and compile it with a C++ compiler, what sort of issues can you expect to crop up? For example, I think that assigning an integer to an value with an enumerated type will fail in C++, whereas it's legal (if a bit nasty) in C.

If I don't wrap all my C files in extern C { ... }, am I going to get name-mangling where I least expect it? Is there some reason why I really shouldn't do this?

For background, we have a very large code-base written in C. For a few years we've been jumping through hoops to do things that would come naturally via C++ ( homebrewe inheritance, for example). We'd like to start moving towards C++, but in a gradual fashion; getting our CORBA-like framework to support it, and refactoring modules as we go along to take advantage of the more natural approach C++ would provide.

解决方案

I've done something like this once. The main source of problems was that C++ is more strict about types, as you suspected. You'll have to add casts where void* are mixed with pointers of other types. Like allocating memory:

Foo *foo;
foo = malloc(sizeof(*foo));

The above is typical C code, but it'll need a cast in C++:

Foo *foo;
foo = (Foo*)malloc(sizeof(*foo));

There are new reserved words in C++, such as "class", "and", "bool", "catch", "delete", "explicit", "mutable", "namespace", "new", "operator", "or", "private", "protected", "friend", etc. These cannot be used as variable names, for example.

The above are probably the most common problems when you compile old C code with a C++ compiler. For a complete list of incompatibilities, see Incompatibilities Between ISO C and ISO C++.

You also ask about name mangling. In absence of extern "C" wrappers, the C++ compiler will mangle the symbols. It's not a problem as long as you use only a C++ compiler, and don't rely on dlsym() or something like that to pull symbols from libraries.

这篇关于我期望用C ++编译器编译C代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆