使用 C++ 编译器编译 C 代码会出现什么问题?

如果您使用现有的 C 代码库并使用 C++ 编译器对其进行编译,您会遇到什么样的问题?例如,我认为将整数分配给具有枚举类型的值在 C++ 中会失败,而在 C 中它是合法的(如果有点讨厌).

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.

如果我不将我所有的 C 文件包装在 extern 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?

作为背景,我们有一个用 C 编写的非常大的代码库.几年来,我们一直在跳槽做一些通过 C++ 很自然的事情(例如,自制继承).我们想开始转向 C++,但要循序渐进;让我们的类似 CORBA 的框架支持它,并在我们进行过程中重构模块以利用 C++ 提供的更自然的方法.

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.

推荐答案

我曾经做过这样的事情.正如您所怀疑的那样,问题的主要来源是 C++ 对类型更加严格.您必须在 void* 与其他类型的指针混合的地方添加强制转换.比如分配内存:

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));

以上是典型的 C 代码,但需要在 C++ 中进行转换:

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

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

C++中有新的保留字,如class"、and"、bool"、catch"、delete"、explicit"、mutable"、namespace"、new"、"operator"、or"、private"、protected"、friend"等.例如,这些不能用作变量名.

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.

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

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++.

您还询问有关名称修改的问题.在没有 extern "C" 包装器的情况下,C++ 编译器 会破坏符号.只要您使用 only 一个 C++ 编译器,并且不依赖 dlsym() 或类似的东西从库中提取符号,这不是问题.

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.

相关文章