7

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.

1
  • @ZanLynx i got the answer it was problem with linker. Commented Sep 15, 2013 at 6:50

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

ok i got this and one more question I have included iostream in both my files. Does that make any problem.
@Nakib iostream won't make any problem. You want to add include guards to your header, though. It's not required yet for the simple example you just posted, but soon enough you will need them, so just make it a habit that all headers should have include guards.
i had edited the code can u check if it is correct. I mean the .h file.
0

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

2 Comments

I think that Makefile needs a bit more explanation, as it invokes some "magic" by not listing the .cpp files at all.
@hyde: Well, there is GNU Make documentation or there are questions and answers here on Stack Overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.