How to Use C Source Files in a C++ Project

How to use C source files in a C++ project?

For the maximum reliability:

  • Compile the C source with a C compiler.
  • Compile the C++ source with a C++ compiler
  • Preferably, write the main() function in C++.
  • Link the program with a C++ compiler.

Make sure that the C headers are either themselves aware of C++ or that the C++ code includes the C headers inside an extern "C" { ... } block.

Either (C header file cheader.h):

#ifndef CHEADER_H_INCLUDED
#define CHEADER_H_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif

...main contents of header...

#ifdef __cplusplus
}
#endif

#endif /* CHEADER_H_INCLUDED */

or (C++ source code):

extern "C" {
#include "cheader.h"
}

Modern C style is very close to the common subset of the C and C++ languages. However, arbitrary C code is not C++ code for any of a very large number of reasons, and simply calling the C source files C++ source files (by changing the extension, or simply by compiling with the C++ compiler) is not guaranteed to be successful. In general, it is easier to compile C as C and C++ as C++ and then link the resulting object files with the C++ compiler (to ensure the correct support libraries are invoked).

However, if the MSVC compiler is saying that programs using MFC have to be written solely in C++ (MFC requires C++ compilation (use a .cpp suffix) is the reported error), then you may have no choice but to ensure that your C code is compilable as C++ code. That means you'll have to cast the return values from malloc() et al; you have to worry about other places where you do not use a cast to convert a void * into some other pointer type; you have to worry about sizeof('a') == 4 in C and sizeof('a') == 1 in C++; you have to ensure that every function is declared before it is used; you have to ensure your C code does not use any C++ keywords (typename, class in particular; also inline sometimes — but the complete list is quite large).

In some circles, you'd have to worry about the use of features in C99 that are not in C++2003 or C++2011, such as flexible array members, designated initializers, compound literals, variable-length arrays, and so on. However, if the C code is for MSVC, then that probably isn't going to be a problem; those features are not supported by the MSVC C compiler (it only supports C89, not C99).

FWIW: I have a script to hunt down C++ keywords. It contains the following comment:

# http://en.cppreference.com/w/cpp/keywords
# plus JL annotations
# and C (<iso646.h>)
# and_eq C (<iso646.h>)
# alignas (C++11 feature)
# alignof (C++11 feature)
# asm C (core)
# auto(1) C (core)
# bitand C (<iso646.h>)
# bitor C (<iso646.h>)
# bool C99 (<stdbool.h>)
# break C (core)
# case C (core)
# catch
# char C (core)
# char16_t (C++11 feature)
# char32_t (C++11 feature)
# class
# compl C (<iso646.h>)
# const C (core)
# constexpr (C++11 feature)
# const_cast
# continue C (core)
# decltype (C++11 feature)
# default(1) C (core)
# delete(1)
# double C (core)
# dynamic_cast
# else C (core)
# enum C (core)
# explicit
# export
# extern C (core)
# false C99 (<stdbool.h>)
# float C (core)
# for C (core)
# friend
# goto C (core)
# if C (core)
# inline C (core)
# int C (core)
# long C (core)
# mutable
# namespace
# new
# noexcept (C++11 feature)
# not C (<iso646.h>)
# not_eq C (<iso646.h>)
# nullptr (C++11 feature)
# operator
# or C (<iso646.h>)
# or_eq C (<iso646.h>)
# private
# protected
# public
# register C (core)
# reinterpret_cast
# return C (core)
# short C (core)
# signed C (core)
# sizeof C (core)
# static C (core)
# static_assert (C++11 feature)
# static_cast
# struct C (core)
# switch C (core)
# template
# this
# thread_local (C++11 feature)
# throw
# true C99 (<stdbool.h>)
# try
# typedef C (core)
# typeid
# typename
# union C (core)
# unsigned C (core)
# using(1)
# virtual
# void C (core)
# volatile C (core)
# wchar_t C (core)
# while C (core)
# xor C (<iso646.h>)
# xor_eq C (<iso646.h>)

The (1) suffixes is a footnote at CPP Reference:

  • (1) — meaning changed in C++11

Can i have multiple C source files in the same project (Visual Studio 19)?

Essentially a Solution is a container used to contain multiple Projects, you can choose to compile either the whole Solution (so all the projects in the solution), or a single Project in said Solution.

Each Project can have only 1 main() because otherwise your OS won't know where to start executing, of course you can have multiple source files in the same project otherwise for even smaller projects you'd have a single file with a huge number of lines.
This structure is quite common in many IDEs (maybe with different names than Project and Solution, this is just a nomenclature that VS uses), it isn't really bound to Windows or Linux in particular.

Try on Linux to have multiple source files with multiple main() and try to compile then together with gcc, you'll see that you get a very similar error.

You also can't have the same function definition in multiple files otherwise you get the LNK 2005 linker error that you've seen. This is because when the Linker is linking your files if it finds two identical definitions it doesn't know which one to take and goes crazy.

But then how do you include the same header files in different sources?

Well that's why .h files have include guards, they ensure that the contents of an .h files are included by the linker only once in each Compilation.

Usually in the header file there is one of two possible ways to include these guards, there are very small differences between these two methods but they don't really apply if you're not doing some very specific stuff:

 #pragma once
// Content of the header

or

#ifndef GUARD_H
#define GUARD_H

// Content of header

#endif

Where GUARD_H should be different for every .h file, usually it's a combination of your Project and header file names just to make sure it's different to other guards that could exist in other headers.

That's also why you can't (and shouldn't) include Source files in your code, if you include a source file then you are at a high risk of including the same definition multiple times since they don't use include guards.

The C file gets stored normally in any folder you want and gets compiled with a gcc and ./a.out in the terminal

That's essentially what VS does, just instead of you choosing which files to add in the compilation VS takes automatically all the files in the same Solution or Project (depending which one you decide to build).

For convenience, if you are just starting to learn, create a new solution for each Project (so for every main()) that you want.

Is this better or worse than using a simple text editor? Well, after the first 10-15 minutes of learning you'll see that it's much faster and useful to use an actual IDE as it provides many features that will make you write code faster and with less errors.

This is a really quick explanation of how things work in general. If you can, try to find someone IRL that can explain these things to you. It's really hard to explain it on the internet but it will take less than 10 minutes being together in front of the same computer.

Why can't I include C files in main.cpp?

The #include directive in C++ is a literal inclusion of source code. Imagine your C source code in Flash.h included by main.c doing something incompatible with C++ like

typedef int class;

Now, in your main.cpp you have

#include "Flash.h"

It's exactly as if you had this code typedef int class; directly in your C++ source file - so it's an error.


If you have C source code with C headers, you don't need to use C++ at all!

If you want to write new C++ code and make it call old code (or vice-versa), just use the linker. Have C++ code include C++ headers, and separately, C code include C headers, and the linker will combine all your code into an executable.


To make your C and C++ parts work together, you need an additional header file. For example call it c-cpp-interface.h. Then include it in all your C and C++ source files:

#include "c-cpp-interface.h" // in C files

extern "C" {
#include "c-cpp-interface.h" // in C++ files
}

This file should be written in a common C/C++ subset language. That is, mostly, C language but with increased type safety (e.g. prototypes for all functions must be written fully, without the implied ... arguments).

Ideally, your existing C header file could be used as such. However, C header files often accumulate cruft, and it might be more practical to create a new file than clean the existing one(s).


Looking at the actual error messages you have (with offsetof), you should try to have as little code as possible in the C - C++ interface. Don't put implementation details (like values of various constants) there. Only have there the declarations/prototypes for functions that are called by the other language (C calling C++ or vice versa).

How can I add C++ Source Files and Headers to a C# .Net project?

Wait, there is a yes answer, but obviously it's completely evil:

How do I mix C# and C++ code in a single assembly?

If your C++ code is not compiled with /clr:safe (i.e. it is compiled with /clr or /clr:pure), do the following:

1) compile your C++ code into .obj files

2) compile your C# code into a .netmodule, using /AddModule to reference the C++ .obj files

3) link the C# netmodule directly with the C++ object files using the C++ linker to create a mixed language assembly

Also this: Linking native C++ into C# applications

Yeah, don't do that.

Can I mix c and cpp files in a C++ project?

extern "C" is one approach. The other approach, assuming your C files are of the (almost ubiquitous) sort which are already compilable as C++, is simply to coerce the compiler into treating them as C++ (which gives them the appropriate name mangling to work with your C++ files). For GCC, this is -x c++.

Multiple source files in a C/C++ Application project ( NetBeans )

For the same project you could have many source files *.c and *.h and others

But for the same project you could have only one main() function in all of the source files

Example:

Code architecture:

.
└── source_folder
├── file1.c
├── file2.c
└── main.c

file1.c

#include <stdio.h>

void printfile1()
{
printf("this is the file1.c\n");
}

file2.c

#include <stdio.h>

void printfile2()
{
printf("this is the file2.c\n");
}

main.c

#include <stdio.h>

void printfile1(); //prototype definition
void printfile2(); //prototype definition

int main()
{
printfile1();
printfile2();
}

How to invoke function from external .c file in C?

Use double quotes #include "ClasseAusiliaria.c" [Don't use angle brackets (< >) ]

And I prefer to save the file with .h extension In the same directory/folder.

TLDR:
Replace #include <ClasseAusiliaria.c> with
#include "ClasseAusiliaria.c"



Related Topics



Leave a reply



Submit