c++多个文件时,函数变量作用域

wangchunlin 2022-8-1 93 8/1

最简单的写法

  • main.cpp
#include<iostream>

void example_func()
{
    // pass
}

int main()
{
    example_func();
    return 0;
}

在A.cpp文件类写函数实现,B.cpp写声明,并在B中直接使用(不用extern,不用include)

  • func.cpp
#include<iostream>

void example_func()
{
    // pass
}
  • main.cpp
#include<iostream>

void example_func();

int main()
{
    example_func();
    return 0;
}

使用extern

  • func.app
#include<iostream>
void example_func();
void example_func()
{
    // pass
}
  • main.cpp
#include<iostream>
extern void example_func();

int main()
{
    example_func();
    return 0;
}

写成头文件形式

  • func.h
#include<iostream>

void example_func();
  • func.cpp
#include "func.h"

void example_func()
{
    // pass
}
  • main.cpp
#include "func.h"

int main()
{
    example_func();
    return 0;
}

引入变量的问题

一个项目里面可能多个H文件会引入同一个H文件,这样在H文件中定义的变量就会重定义,如:

  • A.h
#include<iostream>

DetectTaskList g_DetectTaskList;
  • B.h
#include "A.h"

g_DetectTaskList.use();
  • C.h
#include "A.h"

g_DetectTaskList.use();

编译会产生重定义的错误
处理方式:

  • A.h
#include<iostream>

extern DetectTaskList g_DetectTaskList;
  • A.cpp
#include "A.h"

DetectTaskList g_DetectTaskList;
  • B.h
#include "A.h"

g_DetectTaskList.use();
  • C.h
#include "A.h"

g_DetectTaskList.use();

把函数的定义放在cpp文件中去,H文件用extern表示全局变量,这样include全局变量才不会报错
可以可以这样写呢:

  • A.h
#include<iostream>
DetectTaskList g_DetectTaskList;
extern DetectTaskList g_DetectTaskList;

不行,因为g_DetectTaskList依然被定义了两次
或者这样:

  • A.h
#include<iostream>

extern DetectTaskList g_DetectTaskList;

不定义直接使用extern,会报undefined reference to `g_DetectTaskList'找不到定义这种错误
重点:为了避免多个文件引入H文件重定义的错误,需要使用extern生成全局变量,同时把变量的实际定义放到cpp文件中,这样在引入H文件时,才不会错误;如果不是多个文件引用,应该不会又这么多麻烦,弄清楚变量的作用域即可

- THE END -

wangchunlin

8月02日16:10

最后修改:2022年8月2日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论