Compiling and linking C and C++ files

孤者浪人 提交于 2019-12-11 04:47:26

问题


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.

Assume I have a C file MyProg.c and its corresponding header file MyProg.h.

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

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

EDIT:

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.

SOLUTION:

Utility.h must be removed from Wrapper.h and included in Wrapper.cpp


回答1:


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.

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.

I would write it like this:

g++ -c Utility.cpp
g++ -c Wrapper.cpp
gcc -c MyProg.c
g++ -o MyProg Utility.o MyProg.o Wrapper.o



回答2:


Once you've compiled Wrapper.cpp into object code, it really doesn't matter whether its contents were previously written in C or C++, as long as you use extern "C" to tell the compiler to skip name mangling for func_to_invoke.

If I remember well, both gcc and g++ can detect whether their input files contain C or C++ code and do the right thing, but gcc will link against the C standard library and g++ against C++'s, so it's possible that you end up with some missing functionality.

I think the best course of action would be to use gcc for anything that doesn't use any C++ feature, as it would be the case with C, and g++ for everything else.




回答3:


you should include Utility.o in the last line.



来源:https://stackoverflow.com/questions/22154119/compiling-and-linking-c-and-c-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!