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.
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.
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.
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.
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.
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 -o
filename
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With