《C预处理》之#ifndef

1.test.h

#ifndef TEST_H
#define TEST_H
/*
这里只是说明,在头文件中定义变量是不被推荐的。
*/
int a = 0;
int b = 0;
int c = 0;
int test();
#endif
注意:#ifndef只能防止.h文件被同一个C文件重复包含;不能保证两个C文件对其两次包含,所以如果被一个模块(编译成一个so或bin)中两个c同时包含、并且h文件中有上述定义(非声明)。编译系统就会在链接阶段出错。换句话说:#ifndef是在编译阶段起作用。

这告诉我们:永远不要在.h文件中定义变量!定义变量和声明变量的区别在于定义会产生内存分频操作,是汇编阶段的概念;而声明则只是告诉包含该声明的模块在连接阶段从其他模块寻找外部函数和变量。

但仍然需要注意:声明不一定不是定义,但定义一定是定义!因为有的编译器在int a时已经分配内存,并给予一个零值;但extern一定只是声明。

2.test.c

#include <stdio.h>
/*
如下头文件包含后报错
cc -c main.c test.h
cc -c test.c test.h
cc -o main main.o test.o
test.o:(.bss+0x0): multiple definition of `a'
main.o:(.bss+0x0): first defined here
test.o:(.bss+0x4): multiple definition of `b'
main.o:(.bss+0x4): first defined here
test.o:(.bss+0x8): multiple definition of `c'
main.o:(.bss+0x8): first defined here
*/
//#include "test.h"
extern int a;
extern int b;
extern int c;
int test(){
  a = 5; b = 3; c = 100;
  printf("aadda\n");
  return 0;
}
extern关键字是在模块间链接阶段起作用。

3.main.c

#include "test.h"
#include <stdio.h>

int main(){
  a = 5; b = 3; c = 10;
  printf("aadda\n");
  test();
  return 0;
}

4.Makefile

objects = main.o test.o
default:
	cc -c main.c
	cc -c test.c
	cc -o main $(objects)
clean:
	rm *.o main


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值