zoukankan      html  css  js  c++  java
  • 【c++ primer, 5e】函数声明 & 分离式编译

    p186~p188:

    函数声明
    1、函数只能定义一次,但是可以声明多次。

    2、函数的接口:返回类型 + 函数名 + 形参类型

    3、为什么要在头文件中进行函数声明???在源文件中定义?暂时理解到,这么做可以增强可读性。

    4、含有函数声明的头文件应该被包含到定义函数的源文件中。(例如:#include "diy.h")


    分离式编译 & 6.8 & 6.9


    1、分离式编译:把源文件割成好几块放在不同的文件夹下。最终要生成可执行文件,就必须告诉编译器源文件在哪里。
    具体操作如下:

    >源文件内容(三个文件放在同一个文件夹下面。)

    fact.h

    int fact(int val);

    fact.cpp

    #include "fact.h"
    int fact(int val)
    {
        if (val == 1)
            return 1;
        return val * fact(val - 1);
    }

    factMain.cpp

    #include <iostream>
    #include "fact.h"
    using namespace std;
    int main()
    {
        cout << fact(3) << endl; // output=6
        return 0;
    }

    >开始编译 !

    1)一起编译的方法

    $ g++ factMain.cpp fact.cpp -o lovecpp -std=c++11
    
    $ lovecpp
    6

     2)真*分离式编译

    第一步

    $ g++ -c factMain.cpp
    
    $ g++ -c fact.cpp

    执行这两个操作后会生成fact.o、factMain.o,接下来要把object code(*就是.o文件)链接成可执行文件。

    $ g++ factMain.o fact.o -o lovecpp

    执行后生成lovecpp.exe。这样分几步的好处是:如果修改了其中一个源文件,就重新编译改动的就好了。

     

    6.10

    #include <iostream>
    using namespace std;
    void swap(int *p, int *q)
    {
        int temp;
        temp = *p;
        *p = *q;
        *q = temp;
    }
    int main()
    {
        int a = 3, b = 4;
        cout <<    a << " " << b << endl;
        swap(a , b);
        // 交换之后
        cout <<    a << " " << b << endl;
        /* output:
         3 4
         4 3
         */
        return 0;
    }

     修正:

    #include <iostream>
    using namespace std;
    void swap(int *p, int *q)
    {
        int temp;
        temp = *p;
        *p = *q;
        *q = temp;
    }
    int main()
    {
        int a = 3, b = 4;
        cout << a << " " << b << endl;
        swap(&a , &b);
        // 交换之后
        cout << a << " " << b << endl;
        /* output:
    4
    3
         */
        return 0;
    }

    但是上一个程序也有正确输出??

  • 相关阅读:
    并行和并发
    怎样用第三方开源免费软件portecle从https站点上导出SSL的CA证书?
    我持续推动Rust语言支持Windows XP系统
    Android——4.2.2 文件系统文件夹分析
    hadoop(八)
    自己定义html中a标签的title提示tooltip
    多个返回 顶部的代码
    同学们,OpenCV出3.0了,速去围观!
    hdu1002
    好记性不如烂笔头(一)
  • 原文地址:https://www.cnblogs.com/xkxf/p/6579351.html
Copyright © 2011-2022 走看看