user2803194
user2803194

Reputation: 105

Compilng different .cpp files with headers

I have a problem I am trying to compile multiple files together using GNU g++

We assume there are five files:

main.cpp : the main function 
a.h      : the header file of class A 
a.cpp    : the definition of class A 
b.h      : the header file of class B 
b.cpp    : the definition of class B 

In the program, main.cpp uses class A (thus including a.h) and class A uses class B (thus including b.h).

So in my main I have just added #include "a.h"

and I am trying to compile it using

g++ main.cpp -o main

But this doesnt work. It gives me an "undefined reference to" error. The program gives me the required output though when I compile all the classes together with the header file

Could someone please tell me where I am going wrong

Upvotes: 0

Views: 617

Answers (3)

Raja
Raja

Reputation: 3106

When you build only main.cpp, the compiler doesn't complain because it finds the declarations of the objects and functions you call. The linkers job is to ensure it can find the definitions.

Since you didn't ask to compile & link a.cpp and b.cpp along with main.cpp, you get the "undefined refrence to" error.

The linker is essentially telling you: "Hey, I can't find the definitions for so-and-so functions. The compiler didn't complain since you included the header file which had the declarations."

Edit: After seeing your comment, I can understand your problem. There is a difference between declaration and definition.

The compiler relies of finding declarations to classes, functions, types and variables used. If you didn't include the header file (try it!), you'd get an Undeclared identifier error which is from the compiler.

The linker relies on finding definitions for functions and variables that you use. If you didn't link the required files containing the implementation/definitions, you'd get an Undefined reference to ... error, which is from the linker.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

You need to compile all of the source files:

g++ main.cpp a.cpp b.cpp -o main

If you want to do it in steps, you can do that too:

g++ -c main.cpp -o main.o  # compile
g++ -c a.cpp -o a.o        # compile
g++ -c b.cpp -o b.o        # compile
g++ -o main main.o a.o b.o # link

But what you should be doing is using a proper makefile:

CXXFLAGS = -MMD
OBJECTS = main.o a.o b.o
MAKEDEPS = $(OBJECTS:.o=.d)

main: $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $@ $^

clean:
    rm -f *.d *.o main

.PHONY: clean

-include $(MAKEDEPS)

Example:

$ make
c++ -MMD   -c -o main.o main.cpp
c++ -MMD   -c -o a.o a.cpp
c++ -MMD   -c -o b.o b.cpp
c++ -MMD -o main main.o a.o b.o

Upvotes: 6

Ed Heal
Ed Heal

Reputation: 60007

Please read http://linux.die.net/man/1/g++

You need to compile with -c then link those objects

Upvotes: 0

Related Questions