43

I have a C++ program (.cpp) inside which I wish to use some of the functions which are present inside the C header files such as stdio.h, conio.h, stdlib.h, graphics.h, devices.h etc.

I could include the stdio.h library inside my cpp file as : #include <cstdio>. How do I include the other library files?

How do I add the graphics.h library?

I'm using Microsoft Visual Studio 6.0 Enterprise Edition and also Turbo C++ 3.0.

genpfault
  • 51,148
  • 11
  • 85
  • 139
Arjun Vasudevan
  • 792
  • 4
  • 13
  • 33
  • 3
    This may seem like nitpicking, or it my be a minor grammatical error, but this error often indicates a fundamental misunderstanding of C linkage. You cannot include a library file. You can include the header file. The header is not the library. The library is not the header. You can include the graphics.h header, and then you must link against the library whose API is specified in the header. – William Pursell Dec 31 '10 at 15:26

5 Answers5

72

For a list of C standard C headers (stdio, stdlib, assert, ...), prepend a c and remove the .h. For example stdio.h becomes cstdio.

For other headers, use

extern "C"
{
  #include "other_header.h"
}
Scharron
  • 17,233
  • 6
  • 44
  • 63
50

If you put this inside your headers:

#ifdef __cplusplus
extern "C"
{
#endif

// your normal definitions here

#ifdef __cplusplus
}
#endif

Then it will work for both C and C++ without any problem ...

Hope this helps...:)

Andrea
  • 19,134
  • 4
  • 43
  • 65
Flash
  • 2,901
  • 5
  • 38
  • 55
7

I'm not sure what you need exactly, but if you want to use old fashioned C functions inside you C++ program, you can easy include them by removing the .h and add a "c" prefix.

for example if you want to include math.h use

#include <cmath>
MBZ
  • 26,084
  • 47
  • 114
  • 191
4

Just include them inside a extern "C" block an they should work like expected.

Axel Gneiting
  • 5,293
  • 25
  • 30
1

You can #include them using their original names. #include <stdio.h> works just fine in C++.

Steven
  • 2,538
  • 3
  • 31
  • 40
  • The C standard headers are required to work in standard C++, although you may be putting more than you like into the global namespace. Non-standard headers, like conio.h or graphics.h, may not be set up properly, and may need to be wrapped in `extern "C" { ... }`. Check your implementation documentation. – David Thornley Jul 26 '10 at 17:21