Reputation: 2022
Currently, I'm learning c++ and a question about the modularization process. Suppose I want to write a function to add two or three numbers. For that purpose I've wrote the following header file:
// Sum2.hpp
//
// Preprocessor directives; ensures that we do not include a file twice
// (gives compiler error if you do so)
#ifndef Sum2_HPP
#define Sum2_HPP
/////////// Useful functions //////////////////
// Max and Min of two numbers
double Sum2(double x, double y);
// Max and Min of three numbers
double Sum2(double x, double y, double z);
////////////////////////////////////////////////
#endif
This is just declaration. In a separate file, I specify the functions:
// Sum2.cpp
// Code file containing bodies of functions
//
#include "Sum2.hpp"
/////////// Useful functions //////////////////
// Sum of two numbers
double Sum2(double x, double y)
{
return x+y;
}
// Sum of three numbers
double Sum2(double x, double y, double z)
{
return Sum2(Sum2(x,y),z);
}
And then, in the main programm I want to use these functions:
// main.cpp
#include <iostream>
#include "Sum2.hpp"
int main()
{
double d1;
double d2;
double d3;
std::cout<<"Give the first number ";
std::cin>> d1;
std::cout<<"Give the second number ";
std::cin>> d2;
std::cout<<"Give the third number ";
std::cin>> d3;
std::cout<<"The sum is: "<<Sum2(d1,d2);
std::cout<<"The sum is: "<<Sum2(d1,d2,d3);
return 0;
}
I used g++ -c Sum2.cpp
to generate the object code Sum2.o
. Why is there a reference error when I want to compile and create an executable from the main code, i.e. g++ -o main main.cpp
?
It is working when I compile both at same time, i.e. g++ -o main main.cpp Sum2.cpp
. I thought by creating the object code Sum2.o
and including the header file in main.cpp
the compiler will automatically recognize the object code. Why this is not working?
Upvotes: 3
Views: 2050
Reputation: 45079
// Preprocessor directives; ensures that we do not include a file twice
// (gives compiler error if you do so)
No actually, it won't give a compiler error. It just won't do anything.
As for your actual question, c++ unlike some other languages won't try to find your object files for you. You have to tell the compiler where they are at. For this application you should really compile it like so:
g++ -c main.cpp
g++ -c Sum2.cpp
g++ -o main main.o Sum2.o
The first two actually compile the code. The second links the code together to produce the executable. If you execute
g++ -o main main.cpp Sum2.cpp
The compiler will automatically run both steps for you. It works for a small project, but for larger projects you don't want to run all the steps unless something has changed.
Now, you may think that's a pain. You'd be right. That's why there are various tools like CMake, Scons, Jam, Boost.Build which are designed to make it easier to build C++ projects.
Upvotes: 5