项目的代码是C和C++语言混合编写的,主要是C部分调用C++编写的模块。在一个C++写的头文件xml_definition.h中有#include,在一个C写的头文件中include了这个C++头文件。
在编译时报错 string: No such file or directory
请问应该如何解决这种依赖问题?
项目的代码是C和C++语言混合编写的,主要是C部分调用C++编写的模块。在一个C++写的头文件xml_definition.h中有#include,在一个C写的头文件中include了这个C++头文件。
在编译时报错 string: No such file or directory
这种情况下,需要在C头文件中使用extern "C"来声明包含的C++头文件,并使用g++编译器来编译整个项目。
下面是具体的解决方案:
#ifdef __cplusplus
extern "C" {
#endif
// your code here
#ifdef __cplusplus
}
#endif
这段代码实际上是将C++的代码包裹在一个extern "C"块中,这样C编译器就可以正确处理C++的代码。
extern "C" {
#include "xml_definition.h"
}
// your code here
这样可以让C编译器正确处理C++头文件中的代码,并且可以正确编译整个项目。
g++ -o my_program my_program.c my_c_code.c my_cpp_code.cpp -lstdc++
其中:
这样就可以正确编译整个项目,在链接时也不会有任何问题。
完整的代码示例请见下方:
// xml_definition.h
#ifdef __cplusplus
extern "C" {
#endif
#include <string>
// your code here
#ifdef __cplusplus
}
#endif
// my_c_code.h
extern "C" {
#include "xml_definition.h"
}
// your code here
// my_cpp_code.cpp
#include "xml_definition.h"
// your C++ code here
编译命令:
g++ -o my_program my_program.c my_c_code.c my_cpp_code.cpp -lstdc++
这样就可以解决这种依赖问题了。