首页 > 解决方案 > 如何使用头文件编译 C++ 可执行文件

问题描述

我有三个 C++ 程序

因子.h

#ifndef FACTOR_H
#define FACTOR_H

/**
 * Factor an integer n. Prime factors are saved in flist.
 * If n is zero, return -1. If n is negative, factor -n.
 * If n is 1, return 0 and do not save any primes in flist.
 *
 *
 * @param n the integer we wish to factor
 * @param flist an array to hold the prime factors
 * @return the number of prime factors
 */
long factor(long n, long* flist);

#endif

因子.cpp

#include "factor.h"

long factor(long n, long* flist) {

    // If n is zero, return -1
    if (n==0) return -1;

    // If n is negative, we change it to |n|
    if (n<0) n = -n;

    // If n is one, we simply return 0
    if (n==1) return 0;

    // At this point we know n>1

    int idx = 0;    // index into flist array
    int d = 2;      // current divisor

    while (n>1) {
        while (n%d == 0) {
            flist[idx] = d;
            ++idx;
            n /= d;
        }
        ++d;
    }
    return idx;
}

test_factor.cpp

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

/**
 * A program to test the factor procedure
 */

int main() {

    long flist[100];    // place to hold the factors

    for (long n=1; n<=100; n++) {
        int nfactors = factor(n,flist);
        cout << n << "\t";
        for (int k=0; k<nfactors; k++) cout << flist[k] << " ";
        cout << endl;
    }
}

我能够通过这样做来运行它

g++ -c factor.cpp -o factor
g++ -o test_factor test_factor.cpp factor

我的困惑在第二行。当我为 test_factor 创建可执行文件时,为什么我只需要调用 test_factor.cpp 中的头文件?在 test_factor.cpp 中调用 factor.h 如何告诉编译器 factor 函数是如何定义的?我只是不明白它如何自动识别我传入的因子对象文件包含因子的定义。这对我来说毫无意义。

标签: c++

解决方案


为什么我只需要调用 test_factor.cpp 中的头文件?

由于您仅在 test_factor.cpp 中使用 factor(),因此您需要它的声明,在您的情况下由 factor.h 提供。

在您的示例中,您还在 factor.cpp 中包含了 factor.h 。从技术上讲,那里不需要。然而,它被认为是一种好的做法,因为它允许编译器根据实际函数定义 (factor.cpp) 检查声明 (factor.h),特别是参数的数量及其类型。

在 test_factor.cpp 中调用 factor.h 如何告诉编译器 factor 函数是如何定义的?

链接器的工作是拼接包含 factor() 函数和 main() 函数代码的目标文件。

g++ -c 因子.cpp -o 因子

此步骤 (g++ -c) 将 factor.cpp 编译为名为的目标文件factor(其不可执行)

g++ -o test_factor test_factor.cpp 因子

此步骤 (g++ -o) 编译 test_factor.cpp 并调用链接器将 main() 的目标代码与factor上面生成的代码链接到可执行文件test_factor中。

作为试验,您可以省略factor第二步。它将引发链接器错误。


推荐阅读