头文件不宜定义变量的原因全面解析

时间:2021-05-19

test-1.0使用#ifndef只是防止了头文件被重复包含(其实本例中只有一个头件,不会存在重复包含的问题),但是无法防止变量被重复定义。
复制代码 代码如下:
# vi test.c
-------------------------------
#include <stdio.h>
#include "test.h"

extern i;
extern void test1();
extern void test2();

int main()
{
test1();
printf("ok\n");
test2();
printf("%d\n",i);
return 0;
}


# vi test.h
-------------------------------
#ifndef _TEST_H_
#define _TEST_H_

char add1[] = "\n";
extern void test1();
extern void test2();

int main()
{
test1();
printf("ok\n");
test2();
printf("%d\n",i);
return 0;
}


# vi test.h
-------------------------------
#ifndef _TEST_H_
#define _TEST_H_

extern i;
extern char add1[];
extern char add2[];

void test1();
void test2();

#endif

# vi test1.c
-------------------------------
#include <stdio.h>
#include "test.h"

void test1()
{
printf(add1);
}

# vi test2.c
-------------------------------
#include <stdio.h>
#include "test.h"

void test2()
{
printf(add2);
for (; i > 0; i--)
printf("%d-", i);
}

个人认为解决此类问题有几种办法:
1.在.cpp里定义变量,在其他调用处使用extern
2.在头文件里使用宏定义

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章