C++中的模块化是如何工作的?

3

目前,我正在学习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个回答

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++项目更加容易。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接