1

Stackoverflow won't let me comment because I am a newbie.

Borrowing the title from the question posted here, the accepted solution says that you have to modify the C header file using #ifdef __cplusplus and extern "C". I have the exact same question but I have been provided a C library containing over 100 .h C header files and .c C program files and now I have to use a C++ library so my main() will be in C++.

So do I now have to add those modifications to each one of those C header files or is there some other approach? My main() is in a .cpp file which will use functions from this C library.

EDIT This question has been resolved. I wish for this question to be closed or removed.

2 Answers 2

3

You don't have to modify any headers. What is necessary is to wrap all C declarations with extern C {}. You can do this just as well in you cpp file:

extern "C" { #include "some_c_header.h" } int main() { std::cout << "This is C++ code\n"; } 

It might be useful to create a header file which simply includes C headers with C linkage:

// c_header.hpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "c_header_1.h" #include "c_header_2.h" #ifdef __cplusplus } #endif // main.cpp #include "c_header.hpp" // extern "C" {} already handled for you 
Sign up to request clarification or add additional context in comments.

Comments

1

Only those declarations of C functions and objects that are accessed by C++ components need to declared with C linkage, and only to the C++ components. Presumably, your new C++ library accesses very little, if anything, from the existing C code, so the primary concern would be whatever is accessed (directly) by main(). Those functions must be declared (to main) with C linkage. If that turns out to be a significant number of things then you could consider refactoring to make it fewer.

Moreover, no, you do not need to modify existing header files. The C++ files that reference your C library, and that therefore include some of its headers, can wrap the relevant #include statements an an extern "C" block to take care of the issue.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.