zoukankan      html  css  js  c++  java
  • 关于将函数写入头文件问题(分离式编译)

    如果某些函数在其他很多 cpp 文件中被调用,那么为了避免写大量重复的代码以及让代码量更小一些,我们可以将这些函数写头文件中,然后其他 cpp 文件只需要引用该头文件然后就可以使用包含在头文件中的函数了。

    具体实现方法:

    可以直接将函数的定义写入一个xxx.h文件中
    然后用g++ xxx.h 命令将xxx.h编译一遍
    然后在cpp源文件中用#include"xxx.h"引用即可

    然而上面的方法是存在问题的,如果直接将函数的定义写入头文件中,那么这个头文件如果只同时被一个 cpp 文件引用是可行的,但如果其同时被多个 cpp 文件引用是不行的。因为引用头文件在预编译时直接就将头文件中的内容插入源程序。如果直接将函数定义写在头文件中,然后该头文件被多个 cpp 文件引用,则这些 cpp 文件编译生成的 obj 文件中都含有写在头文件中的函数的定义,所以这些 obj 文件在链接的时候会由于含有重复定义而报错(c++ 中允许变量和函数的申明出现多次,但变量和函数的定义只能出现一次)。

    例如:

     1 //gel.h
     2 
     3 int max_(int a, int b){
     4     return a > b ? a : b;
     5 }
     6 
     7 //test1.cpp 
     8 
     9 #include "gel.h"
    10 #include <iostream>
    11 using namespace std;
    12 
    13 int main(void){
    14     cout << max_(1, 2) << endl;
    15     return 0;
    16 }
    17 
    18 //test2.cpp
    19 
    20 #include <iostream>
    21 #include "gel.h"
    22 using namespace std;
    23 
    24 int main(void){
    25     cout << max_(10, 2) << endl;
    26     return 0;
    27 }

    解决的方法:

    在头文件中只写声明,把定义写到另一个cpp文件中就好啦。。

    引用另一个文件的内容除了以头文件的形式外也可以直接将函数写入一个cpp文件,然后在需要引用的地方加个声明,再链接一下就好啦。。。

    事实上只要符合语法(主要是不重复定义变量,函数等),也可以将一个 cpp 文件通过头文件引入另一个 cpp 文件中。。。

    通常是将函数的声明写入头文件,然后将函数体写到其他 cpp 文件中:

     1 // max.h
     2 int max_(int a, int b);
     3 int max_(int a, int b, int c);
     4 
     5 // a.cpp
     6 #include "max.h"
     7 
     8 int max_(int a, int b){
     9     return a > b ? a : b;
    10 }
    11 
    12 // b.cpp
    13 #include "max.h"
    14 
    15 int max_(int a, int b, int c){
    16     return max_(a, b) > max_(b, c) ? max_(a, b) : max_(b, c);
    17 }
    18 
    19 // c.cpp
    20 #include <iostream>
    21 #include "max.h"
    22 using namespace std;
    23 
    24 int main(void){
    25     int a, b, c;
    26     cin >> a >> b >> c;
    27     cout << max_(a, b) << endl;
    28     cout << max_(a, b, c) << endl;
    29     return 0;
    30 }

  • 相关阅读:
    2021.07.01 学习总结
    2021.06.30 学习总结
    2021.06.29 学习总结
    2021.06.28 学习总结
    ubuntu 安装nginx报错./configure: error: SSL modules require the OpenSSL library
    Docker 启动alpine镜像中可执行程序文件遇到 not found
    docker基于cenots7 制作nginx镜像
    【Linux报错】VM虚拟机的CentOS7系统启动时报Generating /run/initramfs/rdsosreport.txt
    Docker Swarm 集群概念扩展
    Docker Swarm 集群弹性、动态扩缩容
  • 原文地址:https://www.cnblogs.com/geloutingyu/p/7811668.html
Copyright © 2011-2022 走看看