Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is not actual code i am working on but sample code i had written to understand what i am doing wrong. So i have three files main.cpp, favourite.cpp and favourite.h. I am trying to compile main.cpp but get some weird error.

// main.cpp File

#include <iostream>
#include "favourite.h"

using namespace std;

int main()
{
    favNum(12);

}

// favourite.cpp File

#include "favourite.h"
#include <iostream>

using namespace std;

void favNum(int num)
{
    cout << "My Favourate number is " << num << endl;
}

// favourite.h File

#ifndef FAVOURITE_H
#define FAVOURITE_H

void favNum(int num);

#endif

This all files are in same folder and i am compiling it normally like g++ main.cpp I am not sure if i need to compile it diffrently as i am using custom header files.

like image 767
Nakib Avatar asked Sep 15 '13 06:09

Nakib


People also ask

Do you compile header files in C?

c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development. Such a technique basically computed the include statements and kept a cache of the flattened includes.

How do I precompile a header file?

The compiler options for precompiled headers are /Y . In the project property pages, the options are located under Configuration Properties > C/C++ > Precompiled Headers. You can choose to not use precompiled headers, and you can specify the header file name and the name and path of the output file.

What happens if we include a header file twice in C?

If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time. This construct is commonly known as a wrapper #ifndef.

What happens when you include a header file in C?

Including a header file produces the same results as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place.


1 Answers

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

g++ main.cpp favourite.cpp

or split compilation and linking:

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

Where -c means: Compile only, no linking and -ofilename is required because you want to write the output to two different object files to link them with the last command.

You might also add additional flag, the most important ones are:

-Wall -Wextra -O3
like image 83
Daniel Frey Avatar answered Sep 25 '22 15:09

Daniel Frey