编译和链接C和C ++文件 [英] Compiling and linking C and C++ files
问题描述
我想从C文件中调用C ++函数,并且我已经阅读了有关外部 C构造和包装API的信息。但是,我不确定如何组织各种头文件以及如何链接目标文件。
I would like to invoke a C++ function from within a C file and I have read about the extern "C" construct and the wrapper API. However, I am unsure how to organize the various header files and how to link the object files.
假设我有一个C文件 MyProg.c 及其对应的头文件 MyProg.h 。
Assume I have a C file MyProg.c and its corresponding header file MyProg.h.
现在,我创建了两个文件 Wrapper.cpp 和 Wrapper.h ,它们声明了我想调用的函数来自MyProg.c
Now, I created two files Wrapper.cpp and Wrapper.h that declare the function I wish to call from MyProg.c
// Wrapper.h
#include "Utility.h"
#ifdef __cplusplus
extern "C" {
#endif
void func_to_invoke();
#ifdef __cplusplus
}
#endif
请注意,Wrapper.h包含一个包含其他实用C ++函数的文件。
Note that Wrapper.h includes a file that contains other utility C++ functions.
问题是如何编译和链接文件。我应该执行以下操作:
The question is how to compile and link the files. Should I do the following:
g++ -c Utility.cpp Utility.h
g++ -c Wrapper.cpp Wrapper.h Utility.h
gcc -c MyProg.c MyProg.h Wrapper.h
gcc MyProg.o Wrapper.o
编辑:
我尝试了以下操作,但仍然无法编译。我的页面和与C ++库相关的错误页面。我还应该在__cplusplus宏中声明Utility.h中的所有功能吗?
I have tried the following and I still can't compile. I have pages and pages of errors related to the C++ libraries. Should I also declare all the functions in Utility.h within a __cplusplus macro?
g++ -c Utility.cpp
g++ -c Wrapper.cpp
gcc -c MyProg.c
g++ MyProg.o Wrapper.o Utility.
解决方案:
Utility.h必须从Wrapper.h中删除并包含在Wrapper.cpp中。
Utility.h must be removed from Wrapper.h and included in Wrapper.cpp
推荐答案
请勿包括.cpp包装器标题中的文件。那完全是错误的事情。甚至不包含Utility.h标头。只需定义包装函数即可。然后在Wrapper.cpp中包含Utility.h标头并定义包装函数。
Do not include a .cpp file in your Wrapper header. That is entirely the wrong thing to do. Do not even include the Utility.h header. Just define your wrapper function. Then in Wrapper.cpp include the Utility.h header and define the wrapper function.
如果您的C ++代码使用异常或运行时类型信息,则需要做最后的链接使用g ++。您的程序将需要C ++支持库。
If your C++ code uses exceptions or runtime type information you will need to do the final link with g++. Your program will need the C++ support library.
我会这样写:
g++ -c Utility.cpp
g++ -c Wrapper.cpp
gcc -c MyProg.c
g++ -o MyProg Utility.o MyProg.o Wrapper.o
这篇关于编译和链接C和C ++文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!