Error compiling source file and header file together in C ++

This is not the actual code I'm working on, but an example of the code I wrote to understand what I'm doing wrong. Therefore, I have three main.cpp , favorite.cpp and favorite.h files. I am trying to compile main.cpp but get some weird errors.

// file main.cpp

#include <iostream> #include "favourite.h" using namespace std; int main() { favNum(12); } 

// file favorite.cpp

 #include "favourite.h" #include <iostream> using namespace std; void favNum(int num) { cout << "My Favourate number is " << num << endl; } 

// file favorite.h

 #ifndef FAVOURITE_H #define FAVOURITE_H void favNum(int num); #endif 

All files are in the same folder, and I usually compile it as g ++ main.cpp . I'm not sure what I need to compile it as I use custom header files.

+4
source share
2 answers

If you say g++ main.cpp and this is your whole command line, the error is a linker error that it cannot find favNum , right? In this case, try:

 g++ main.cpp favourite.cpp 

or compile compilation and binding:

 g++ -c main.cpp -o main.o g++ -c favourite.cpp -o favourite.o g++ main.o favourite.o 

Where -c means: only compilation, no binding required and -o filename , because you want to write the output to two different object files in order to link them to the last command.

You can also add an additional flag, the most important of which are:

 -Wall -Wextra -O3 
+5
source

Oh, I think I see a mistake, although you should have included it in your question.

When compiling multiple source files, you need to list them all on the GCC command line. Or you can use a makefile.

So you can do this:

 g++ favourite.cpp main.cpp 

Or you can write a Makefile as follows:

 all: program program: main.o favourite.o 

And then just type:

 make 
0
source

Source: https://habr.com/ru/post/1502231/


All Articles