一般,我们总会把声明放在头文件,定义和实现放在cpp文件中
如果头文件里有了实现,会报重定义错误
造成这个链接错误很容易。。。
三个文件
test.h
#ifndef TEST
#define TEST
char* str = "abc";
void fun();
#endif
test.cpp
#include"test.h"
#include<iostream>
using namespace std;
void fun()
{
cout<<str<<endl;
}
main.cpp
#include"test.h"
int main()
{
fun();
return 0;
}
解决方案
有两个常用的,一个是extern 一个是 static
他们是互斥的
static 很容易 直接在上面代码里加就好了
因为static变量需要在声明时赋值,且会存在静态区,程序结束前才释放,程序能找到它,就不会报错。
extern用法:
头文件里的声明加 extern
#ifndef TEST
#define TEST
//static char* str = "abc";
extern char* str;
void fun();
#endif
cpp里定义
#include"test.h"
#include<iostream>
using namespace std;
char* str = "abc";
void fun()
{
cout<<str<<endl;
}
这时他们用的是同一块空间,就不会有重定义的问题了