模块化如何在c ++中运行

时间:2013-11-17 15:24:22

标签: c++

目前,我正在学习c ++和关于模块化过程的问题。假设我想编写一个函数来添加两个或三个数字。为此,我写了以下头文件:

// 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

这只是声明。在单独的文件中,我指定了函数:

// 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);
}

然后,在主程序中我想使用这些函数:

// 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;
}

我使用g++ -c Sum2.cpp生成目标代码Sum2.o。当我想从主代码编译和创建可执行文件时,为什么会出现引用错误,即g++ -o main main.cpp

当我同时编译两个时,它正在工作,即g++ -o main main.cpp Sum2.cpp。我想通过创建目标代码Sum2.o并在main.cpp中包含头文件,编译器将自动识别目标代码。为什么这不起作用?

1 个答案:

答案 0 :(得分:5)

// Preprocessor directives; ensures that we do not include a file twice
// (gives compiler error if you do so)

实际上,它不会给编译器错误。它不会做任何事情。

至于你的实际问题,与其他语言不同,c ++不会试图为你找到你的目标文件。你必须告诉编译器他们在哪里。对于这个应用程序,你应该像这样编译它:

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

前两个实际编译代码。第二个将代码链接在一起以生成可执行文件。如果你执行

g++ -o main main.cpp Sum2.cpp

编译器会自动为您执行这两个步骤。它适用于小型项目,但对于较大的项目,除非发生变化,否则不希望运行所有步骤。

现在,你可能会觉得这很痛苦。你是对的。这就是为什么有各种工具,如CMake,Scons,Jam,Boost.Build,旨在使构建C ++项目更容易。

相关问题