C++知识点 单独编译总结

作为一个工业级的高级编程语言,C++和C语言一样,也提供了单独编译的能力,即将组件函数放在独立的文件中,单独编译这些文件,然后再将它们链接为可执行的程序。
**如果只修改了项目中的一个文件,则可以重新编译该文件,然后将它与其他文件的编译版本链接。**例如,make 可以跟踪程序的依赖文件以及这些文件的最后修改时间。运行make时,如果它检测到上次遍以后修改了源文件,make将记住重新构建程序所需要的步骤。

简单介绍

一般程序可以分为三类:

  • 头文件:包含结构,对象声明和使用这些结构,对象的函数的原型
  • 源代码文件:包含与结构,对象有关的函数的代码
  • 源代码文件:包含调用与结构,对象有关的函数的代码

头文件中一般包含的内容:

  • 函数原型
  • 使用#define或const定义的符号常量
  • 结构声明
  • 类声明
  • 模板声明
  • 内联函数
    结构/类声明不会创建变量,而指示在源代码文件中声明结构/类变量时告诉编译器如何创建该结构变量。
    模板声明不是将被编译的代码,它指示编译器如何生成与源代码中的函数调用相匹配的函数定义。
    被声明为 const 的数据和内联函数有特殊的链接属性(内链接),可以防在头文件中。

代码示例

1.先定义头文件 coordin.h

//
// Created by 周天斌 on 2022/1/26.
//

#ifndef CPP_PRACTICE_COORDIN_H
#define CPP_PRACTICE_COORDIN_H

struct polar {
    // distance from origin
    double distance;
    // direction from origin
    double angle;
};

struct rect {
    // horizontal distance from origin
    double x;
    // vertical distance from origin
    double y;
};

// prototypes
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);

#endif //CPP_PRACTICE_COORDIN_H

注意头文件中使用了 ifndefendif的预处理器编译指令,这样可以保证同一个结构只被定义一次,防止编译错误,但是不能防治同样的结构在头文件中出现多次,如果出现多次就取第一次的定义。

2.定义源文件 file1.cpp 和 file2.cpp

// file1.cpp
#include <iostream>
#include "coordin.h"

int main() {
    rect rplace;
    polar pplace;

    std::cout << "Enter the x and y values: ";
    while (std::cin >> rplace.x >> rplace.y) {
        pplace = rect_to_polar(rplace);
        show_polar(pplace);
        std::cout << "Next two numbers (q to quit)";
    }
    std::cout << "Bye\n";
    return 0;
}
// file2.cpp
#include <iostream>
#include <cmath>
#include "coordin.h"

polar rect_to_polar(rect xypos) {
    polar answer;

    answer.distance = std::sqrt(xypos.x * xypos.x + xypos.y * xypos.y);
    answer.angle = atan2(xypos.x, xypos.y);
    return answer;
}

void show_polar(polar dapos) {
    const double Rad_to_deg = 57.29577951;

    std::cout << "distance = " << dapos.distance;
    std::cout << ", angle = " << dapos.angle * Rad_to_deg;
    std::cout << " degrees\n";
}

编译执行:g++ file1.cpp file2.cpp -o file
在这里插入图片描述
注意:

  • 虽然在本文中使用单独编译来形容这一功能,但是C++标准使用了术语:翻译单元(translator unit)。
  • 当涉及多个库的链接是,最好保证这些库以及源代码都是使用同一个编译器编译,因为每个编译器对名称修饰的功能有自己的实现。

Reference

1.《C++ Primer plus》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值