Compiling and linking C and C++ files

2019-07-23 10:19发布

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

3条回答
聊天终结者
2楼-- · 2019-07-23 10:52

you should include Utility.o in the last line.

查看更多
地球回转人心会变
3楼-- · 2019-07-23 10:55

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
查看更多
beautiful°
4楼-- · 2019-07-23 11:06

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.

查看更多
登录 后发表回答