美文网首页
C语言:认识条件编译

C语言:认识条件编译

作者: 橡树人 | 来源:发表于2020-04-07 07:16 被阅读0次

条件编译使用举例

例1 编写可移植到不同机器或者操作系统上的程序

#if defined(WIN32)
...
#elif defined(MAC_OS)
...
#elif defined(LINUX)
...
#endif

例2 编写支持不同编译器的程序

#if __STDC__
Function prototypes
#else 
old-style function declarations
#endif

例3 提供一个默认的宏定义

#ifndef BUFFER_SIZE
#define BUFFER_SIZE 256
#endif

例4 暂时屏蔽注释的代码

#if 0
包含注释的行
#endif

例5 防止同一个头文件被多次包含

假设file1.h包含file3.hfile2.h包含file3.hprog.c同时包含file1.hfile2.h,如果不进行处理,则编译prog.c时,file3.h就会被编译两次,并会报错。

源文件prog.c

#include <stdio.h>
#include "file1.h"
#include "file2.h"

int main(void)
{
    printf("test in prog.c\n");
    return 0;
}

源文件file1.h


#include "file3.h"

void h(void)
{
    g();
}

源文件file2.h


#include "file3.h"

void test2(void)
{

    g();
}

源文件file3.h

#include <stdio.h>

#define TEST 0

void f(void);

int test = 0;

void g(void)
{
    printf("test in file3.c\n");
}

此时,执行如下指令,有报错输出:

$ gcc -c prog.c file1.h file2.h file3.h
In file included from prog.c:3:
In file included from ./file2.h:2:
./file3.h:7:5: error: redefinition of 'test'
int test = 0;
    ^
./file1.h:2:10: note: './file3.h' included multiple times, additional include
      site here
#include "file3.h"
         ^
./file2.h:2:10: note: './file3.h' included multiple times, additional include
      site here
#include "file3.h"
         ^
./file3.h:7:5: note: unguarded header; consider using #ifdef guards or #pragma
      once
int test = 0;
    ^
In file included from prog.c:3:
In file included from ./file2.h:2:
./file3.h:9:6: error: redefinition of 'g'
void g(void)
     ^
./file3.h:9:6: note: previous definition is here
void g(void)
     ^
2 errors generated.

解决方法:
file3.h中添加如下的预处理指令

#ifndef FILE3_H
#define FILE3_H

... //这里是原file3.h的内容

#endif

修改后的file3.h文件,然后编译通过:

#ifndef FILE3_H
#define FILE3_H

#include <stdio.h>

#define TEST 0

void f(void);

int test = 0;

void g(void)
{
    printf("test in file3.c\n");
}
#endif

相关文章

网友评论

      本文标题:C语言:认识条件编译

      本文链接:https://www.haomeiwen.com/subject/rtnwphtx.html