user1536030
user1536030

Reputation: 21

Multi-file C++ compilation

(hopefully) quick question that I can't find the answer to:

I have been given a brief assignment in C++. We are to write a 3-file program. There will be a function file, a header file, and a driver file. Here's what I've got so far:

Header (test.h):

#include <iostream>
using namespace std;
#ifndef TEST_H
#define TEST_H

int foo (int bar);

#endif

Function (test.cpp):

#include <iostream>
#include "test.h"
using namespace std;

int foo (int bar){
    bar++;
}

Driver (drive.cpp):

#include <iostream>
#include "test.h"
using namespace std;

int main(){
    int x = foo(2);
    cout << x << endl;
    return x;
}

When I try to compile drive.cpp, I get the following error:

drive.cpp:(.text+0xe): undefined reference to `foo(int)'

So...what am I doing wrong?

Upvotes: 0

Views: 142

Answers (4)

Fredrick Gauss
Fredrick Gauss

Reputation: 5166

in test.cpp, change the return line to this:

return bar++;

Upvotes: 1

Natan Streppel
Natan Streppel

Reputation: 5866

In drive.cpp, instead of

#include <test.h>

make it

#include "test.h"

This is the variant of #include syntax that is used for header files of your own program (not system header files). When you use this version the preprocessor searches for include files in the following order:

  • In the same directory as the file that contains the #include statement.

  • In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first.

Upvotes: 2

kfsone
kfsone

Reputation: 24249

You need to do one of two things:

Compile all the files at once

# replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o driver.exe main.cpp driver.cpp

Compile all the files to object files and then link the object files:

# again, replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o main.o -c main.cpp
g++ -Wall -ggdb -o driver.o -c driver.cpp
g++ -Wall -ggdb -o driver.exe main.o driver.o

As a side note, you should probably change

#include <test.h>

to

#include "test.h"

and putting "using namespace std;" in a header file is going to cause you copious grief later on.

Upvotes: 1

Adam
Adam

Reputation: 17329

For a small project like this, simply compile all .cpp files at once:

g++ main.cpp driver.cpp

For a larger project, you separate the compile and link steps:

compile:

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

link:

g++ main.o driver.o

Or rather, you'd have a makefile or IDE do this for you.

Upvotes: 4

Related Questions