0

I am working on a project where half my code is in c and half is in c++.

Now I want to include the cprogram.c in my cppprogram.cpp.

When including a c file inside a c program you can use

#include "cprogram.c"

Anyways to do that in c++ for including a c program.

  • 5
    You should never #include a *.c file. Doing it across languages is even worse. – William Pursell Mar 16 '21 at 18:14
  • You can do that, if and only if the code in that file can be compiled as C++ (the compiler doesn't care about the `.c` extension). So, in other words, it must be valid C++ as well. However, normally you don't mix things like that and if you mix C and C++ you compile them separately. All that said, you don't ask a question. Please, as a new user here, start with the [tour] and read [ask]. – Ulrich Eckhardt Mar 16 '21 at 18:15
  • *"When including a c file inside a c program"* - that's *not* how one normally includes a .c file in a C program. It is normally part of the compile source files list that are individually built, usually as part of a build pattern such as a Makefile, a CMakeLists.txt, a visual studio project file, etc. And `#include`-ing a .c file in a c++ source file (.cpp/.cxx) is at best a gamble. C and C++ are different languages. There is a *chance* it will "work" (term used very loosely). You're probably better off incorporating the file properly as a C source, compiled as C target in your build system. – WhozCraig Mar 16 '21 at 18:16

2 Answers2

2

Besides from that you normally don't include .c files, but .h files instead, and that the following is bad practice, you can include C files into .cpp / .hpp files by wrapping the include into an extern "C":

cppprogram.cpp

extern "C" {
#include "cprogram.c"
}

See here for some examples.

TheEagle
  • 5,808
  • 3
  • 11
  • 39
0

As long as you are using Make or Cmake, you can just add it with #include "cprogram.c". C++ is also compatiable with C so you can just add it.