简体   繁体   English

C预处理器如何工作

[英]C preprocessor how it works

i have the following files 我有以下文件

(its pseudo code, and i know the define, undef is ugly, but i would need it for some project) (它的伪代码,而且我知道定义,undef很丑陋,但对于某些项目,我将需要它)

if i compile those files and link them together - it seems to work - that in file3, file1 - MYVAL == 1 如果我编译这些文件并将它们链接在一起-似乎可以正常工作-在file3,file1中MYVAL == 1

is it safe to assume this, that the preprocessor stuff is done file-by-file? 可以安全地假设预处理程序是逐文件完成的吗?

conf.h: conf.h:

#define MYVAL 1

src1.c src1.c

#include "conf.h"
int maint(int argc, char ** argv) {
    printf("%d", MYVAL);
}

src2.c src2.c

#include "conf.h"
void demo() {
    #undef MYVAL
    #define MYVAL 2
    printf("%d", MYVAL);
}

src3.c src3.c

  #include "conf.h" 
  void demo2() {
       printf("%d", MYVAL);
  }

regards 问候

Preprocessing is done per translation unit before the compilation phase (so way earlier than the linkage phase). 在编译阶段之前(因此比链接阶段更早)在每个翻译单元中进行预处理。 In your case the preprocessor will expand that macro in each of your .c files individually based on your inclusion of the conf.h header file. 在您的情况下,预处理程序将根据您是否包含conf.h头文件来分别在每个.c文件中扩展该宏。

is it safe to assume this, that the preprocessor stuff is done file-by-file? 可以安全地假设预处理程序是逐文件完成的吗?

Basically in your case yes. 基本上是您的情况。 Each of your .c files is a distinct translation unit. 每个.c文件都是一个不同的翻译单元。 (Unless they start including each other or something) They are preprocessed separately, compiled and then their objects get linked together. (除非它们开始彼此包含或包含其他内容),将它们分别进行预处理,编译,然后将它们的对象链接在一起。

When you #include "conf.h" its code is placed instead of this line. 当您#include "conf.h"将放置其代码而不是此行。 This is the preprocessor's work. 这是预处理器的工作。 So, this define sentence is placed in each file. 因此,该define语句放置在每个文件中。

But if you do #define work(n) funcCall((n)) and work(5); 但是如果您#define work(n) funcCall((n))work(5); then, it'll fail if funcCall is not defined in any of your files. 然后,如果未在任何文件中定义funcCall ,它将失败。

Yes, the preprocessor is used for each source file. 是的,每个源文件都使用预处理器。 It generates a preprocessed file from the source file and all include files that is actually passed to the C compiler. 它从源文件生成一个预处理文件,并且所有包含文件都实际传递给C编译器。

When you #define something in a include file it gets in the preprocessed file. 当您在包含文件中#define某些内容时,它会进入预处理文件中。 #define s in other source file doesn't care. 其他源文件中的#define不在乎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM