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.

3
  • 5
    You should never #include a *.c file. Doing it across languages is even worse. Commented Mar 16, 2021 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 How to Ask. Commented Mar 16, 2021 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. Commented Mar 16, 2021 at 18:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.