Nakib
Nakib

Reputation: 4703

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.

Upvotes: 7

Views: 8604

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54325

Oh I guess I see the error 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 could do this:

g++ favourite.cpp main.cpp

Or you could write a Makefile like this:

all: program
program: main.o favourite.o

And then just type:

make

Upvotes: 0

Daniel Frey
Daniel Frey

Reputation: 56863

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

Upvotes: 5

Related Questions