0

I'm having a custom C header file that I have created. There are several files in my directory as follows.

lib1/
     -lib1.h
     -lib1.c
lib2/
     -lib2.h
     -lib2.c
-lib_main.c
-lib_main.h
-main.c
-main.cpp
-Makefile

Now, for testing the header file with a test file called main.c, I will be giving the following command in the terminal,

gcc lib_main.c lib1/lib1.c lib2/lib2.c main.c -o ./main

Now, how could I test the same header files with main.cpp instead of main.c, how do I change it?

  • Presumably you'd just substitute `main.cpp` for `main.c` in that command, however you really shouldn't mix C and C++ like that. Compile each file individually, then *link* them together. Find a good `Makefile` template, or CMake if you prefer, as a way to do this reliably. – tadman Jun 01 '21 at 06:59
  • Could you explain me how to compile them seperately and link them? – Vigneshwar Ravichandar Jun 01 '21 at 07:01
  • Pick your favorite [Makefile template](https://spin.atomicobject.com/2016/08/26/makefile-c-projects/) and build up from there. The idea is you compile each file in the correct language mode, C or C++ accordingly, then combine them into the final executable. – tadman Jun 01 '21 at 07:03

1 Answers1

2

You should (and most probably must) compile separately the c and c++ sources into a object file, and then link together.

As an example

gcc -c -o lib1.o lib1/lib1.c
gcc -c -o lib2.o lib2/lib1.c
gcc -c -o lib_main.o lib_main.c
g++ -c -o main.o main.cpp
g++ -o main lib1.o lib2.o lib_main.o main.o

The first four commands create a series of object files, with extension .o. The last command link together the object files into an executable. Obviously you need to add the relevant compiler options for each source.

Two important points to notice:

  • Order of files in the linking is important. See discussion here and here.

  • To mix c and c++ code with each other, for example if a c++ code calls a c function, you need to follow specific guidelines.

francesco
  • 7,189
  • 7
  • 22
  • 49