How to inlcude C header files in C++
Related Blog Items
- C++ Advanced Tutorial - Lesson 6
- Sorting a Linked List with Selection Sort
- Swapping nodes in a single linked list
- Writing a simple make file with example
- C++ Basics Tutorial - Lesson 11
There are two ways to do this
1)
If you are including a C header file that isn’t provided by the system, you may need to wrap the #include line in an extern “C” { /*…*/ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.
// This is C++ code
extern ”C” {
// Get declaration for f(int i, char c, float x)
#include ”my-C-code.h”
}
2)
If you are including a C header file that isn’t provided by the system, and if you are able to change the C header, you should strongly consider adding the extern “C” {…} logic inside the header to make it easier for C++ users to #include it into their C++ code. Since a C compiler won’t understand the extern “C” construct, you must wrap the extern “C” { and } lines in an #ifdef so they won’t be seen by normal C compilers.
Step #1: Put the following lines at the very top of your C header file (note: the symbol __cplusplus is #defined if/only-if the compiler is a C++ compiler):
extern ”C” {
#endif
Step #2: Put the following lines at the very bottom of your C header file:
}
#endif
Now you can #include your C header without any extern “C” nonsense in your C++ code:
// This is C++ code
// Get declaration for f(int i, char c, float x)
#include ”my-C-code.h” // Note: nothing unusual in #include line
Popularity: 5%
You need to log on to convert this article into PDF
Related Blog Items - C++ Advanced Tutorial - Lesson 6
- Sorting a Linked List with Selection Sort
- Swapping nodes in a single linked list
- Writing a simple make file with example
- C++ Basics Tutorial - Lesson 11
Related Blog Items
- C++ Advanced Tutorial - Lesson 6
- Sorting a Linked List with Selection Sort
- Swapping nodes in a single linked list
- Writing a simple make file with example
- C++ Basics Tutorial - Lesson 11
No Comments
No comments yet.