我正在尝试编写一个C++代码,我称之为C函数,让我们说hello_world()
这又调用了一个用户定义的typename()函数.当我在C++中包含我的C代码时,有一个编译错误,我知道这typename是C++中的一个关键字,但后来包含C代码,我正在使用
extern "C" { #include "hello_world.h"}
Run Code Online (Sandbox Code Playgroud)
在我的C++代码中,仍然在编译期间出现错误,任何避免这种情况并编译代码的建议,我将不胜感激.
我无法将用户定义typename()函数的名称更改为其他名称.那怎么去......?
这样的错误:
In file included from New_test.cpp:19:0:
../tools/symbol.h:38:14: error: expected unqualified-id before ‘typename’
../tools/symbol.h:38:14: error: expected initializer before ‘typename’
In file included from New_test.cpp:604:0:
/usr/include/i386-linux-gnu/sys/poll.h: In function ‘int readpacket(channel*, void*, size_t)’:
/usr/include/i386-linux-gnu/sys/poll.h:48:1: error: expected unqualified-id before string constant
New_test.cpp:612:52: error: ‘poll’ was not declared in this scope
您可能需要在头文件中使用以下内容:
文件:common_header.h
#ifdef __cplusplus
extern "C" {
#endif
extern void newname_typename();
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
然后是一个只有C的编译单元:
#include "common_header.h"
#include "hello_world.h"
void newname_typename() {
typename();
}
Run Code Online (Sandbox Code Playgroud)
在C++中:
#include "common_header.h"
void do_stuff() {
newname_typename();
}
Run Code Online (Sandbox Code Playgroud)
并且您需要确保您的Makefile最终执行以下操作:
gcc c_only_code.c -o something1.o
g++ cplus_only_code.cxx -o something2.o
gcc something1.o something2.o <other stuff> -o binary
Run Code Online (Sandbox Code Playgroud)
以下是如何对事物进行分区以便正确编译和链接的方法.C++源文件不需要知道有一个函数被调用typename().
档案' some_c.c':
#include "some_c.h"
void typename(); /* This declaration will suffice. */
void hello_world()
{
typename();
}
Run Code Online (Sandbox Code Playgroud)
档案' some_c.h'
/* References to typename()'s declaration must be deleted from this
** header file. If it turns out that there are some other parts of the
** header file which somehow depend on the typename() declaration, you
** must separate this into multiple header files.
*/
void hello_world();
Run Code Online (Sandbox Code Playgroud)
档案' some_cpp.cpp':
/* Arguably this should show up in some_c.h, protected by
** #ifdef __cplusplus barriers. But this should work too:
*/
extern "C" {
#include "some_c.h"
}
void SomeClass::someMethod()
{
hello_world();
}
Run Code Online (Sandbox Code Playgroud)