Go to the first, previous, next, last section, table of contents.


Transformations Made Globally

Most C preprocessor features are inactive unless you give specific directives to request their use.

대부분의 C 전처리기는  그것들의 사용을 요청하는 특정 지시문을 주지 않는 한 활동하지 않는다.

(Preprocessing directives are lines starting with a `#' token, possibly preceded by whitespace; see section Preprocessing Directives).

(전처리 지시문들은 라인 처음에 `#' 토큰으로 시작한다. 공백이 오는 것도 가능하다.)

However, there are four transformations that the preprocessor always makes on all the input it receives, even in the absence of directives. These are, in order:

그러나 지시문이 없어도 모든 입력을 전처리기가 처리하는 네 가지 변형된 모양이 있다.

For end-of-line indicators, any of \n, \r\n, \n\r and \r are recognised, and treated as ending a single line. As a result, if you mix these in a single file you might get incorrect line numbering, because the preprocessor would interpret the two-character versions as ending just one line. Previous implementations would only handle UNIX-style \n correctly, so DOS-style \r\n would need to be passed through a filter first.

end-of-line 지시문을 위해, \n, \r\n, \n\r 그리고 \r 이 인정 되고  한 라인의 끝으로써 다루어진다. 전처리기는 라인의 끝으로써 두 가지 문자 버전을0 해석하기 때문에, 만약 이것들을 섞어 쓴 다면, 부정확한 라인 수를 얻게 될 것이다. 이전에는  정확하게 유닉스 스타일인 \n만을 다루었다. 그래서 DOS DOS-style \r\n은 처음에 필터로 걸러지는 것이 필요했다.

 

The first three transformations are done before all other parsing and before preprocessing directives are recognized. Thus, for example, you can split a line mechanically with backslash-newline anywhere (except within trigraphs since they are replaced first; see below).

처음 새 가지의 변형은 모두 다른 어구의 parsing과 지시문들을 미리 조사·분석하는 것이 인식되기 전에 수행된다.게다가 ,예를 들면, 당신은 어디든지 backslash-newline로 기계적으로 라인을 나눌 수 있다..

/*
*/ # /*
*/ defi\
ne FO\
O 10\
20

is equivalent into `#define FOO 1020'.

There is no way to prevent a backslash at the end of a line from being interpreted as a backslash-newline. For example,

backslash-newline로 해석되는 라인의 끝에 백슬래시를 막을 필요는 없다..예를 들면,

"foo\\
bar"

is equivalent to "foo\bar", not to "foo\\bar". To avoid having to worry about this, do not use the GNU extension which permits multi-line strings. Instead, use string constant concatenation:

foo\\bar가 아니라 foo\bar와 같다.이것에 대한 걱정을  피하기 위해  multi-line에 스트링을  가능케 한 GNU 확장을 사용하지 마라.대신에, 스트링 상수 연결을 사용하시오.

   "foo\\"
   "bar"

Your program will be more portable this way, too.

당신의 프로그램은 이런 방법에 또한 더 가용적일 것이다.

There are a few things to note about the above four transformations.

네 가지 변형에 대해 주의 해야 할 몇 가지가 있다.

The preprocessor handles null characters embedded in the input file depending upon the context in which the null appears. Note that here we are referring not to the two-character escape sequence "\0", but to the single character ASCII NUL.

전처리기는 null문자들을  null이 나타나는 문맥을 갖는 입력 파일들에 끼워 넣는다. 여기에 우리들이 two-character 탈출 로" \0 "가 아니라 하나의 아스키 NUL로 생각하는 것에 주의 하라..

There are three different contexts in which a null character may appear:

null 문자가 나타날 만한 세가지 다른 문맥이 있다.

        는 아래와 같다

        그리고 X는 1로 대체되는 것으로 정의 된다.

Preprocessing Directives

Most preprocessor features are active only if you use preprocessing directives to request their use.

대부분의 전처리기는 사용하기 위해 전처리 지시문을 사용해야만 활성화 된다.

Preprocessing directives are lines in your program that start with `#'. Whitespace is allowed before and after the `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive that defines a macro.

전처리 지시문은 `#'과 함께 프로그램 라인에 있다. `#' 뒤와 전에 공백은 허락된다. `#' 뒤에는 직접적인 이름 식별자가 따른다. 예를 들어 `#define'은 매크로를 정의 하는 것을 지시 한다.

Since the `#' must be the first token on the line, it cannot come from a macro expansion if you wish it to begin a directive. Also, the directive name is not macro expanded. Thus, if `foo' is defined as a macro expanding to `define', that does not make `#foo' a valid preprocessing directive.

`#'이 라인에 첫번째 토큰이 되어야 하기 때문에, 만약  지시문을 시작하기를 바라면 그것은 매크로 확장부터 올 수 없다.또한, 지시문 이름은 확장된 매크로가 아니다. 이처럼 `foo'는 `define'에서 확장된 매크로로서 정의 되면, `#foo'는 정당한 전처리 지시문이 아니다.

The set of valid directive names is fixed. Programs cannot define new preprocessing directives.

확실한 근거가 있는 지시문 이름들의 set는 고정된다. 프로그램들은 새로운 전처리 지시문들을 정의 할 수 없다.

Some directive names require arguments; these make up the rest of the directive line and must be separated from the directive name by whitespace. For example, `#define' must be followed by a macro name and the intended expansion of the macro. See section Object-like Macros.

몇몇 지시문 이름들은 인자들을 요구한다; 이것들은 지시문 라인의 나머지를 만들고 공백에 의해서 지시문 이름으로부터 분리되어야 한다.예를 들면, '#define'는 매크고 이름이고  매크로에서 의도된 확장이 뒤따라야 한다. Object-like Macros.부분을 봐라

A preprocessing directive cannot cover more than one line. It may be logically extended with backslash-newline, but that has no effect on its meaning. Comments containing newlines can also divide the directive into multiple lines, but a comment is replaced by a single space before the directive is interpreted.

전처리 지시문은 한 라인보다 많을 수 없다.그것은 논리적으로backslash-newline로  확장될지도 모르지만, 그것의 의미는 아무 영향을 끼치지 않는다.. newlines를 담고 있는 주석은 또한 여러 개 라인으로 지시문을 나눌 수 있지만 주석은 지시문이 해석되기 전에 한 공간으로 바뀐다.

 

Header Files

A header file is a file containing C declarations and macro definitions (see section Macros) to be shared between several source files. You request the use of a header file in your program with the C preprocessing directive `#include'.

헤더 파일은 몇몇 소스 파일들사이에 공유되기 위하여 C 선언들 그리고 매크로 정의(탐색 섹션 Macros)를 포함한 파일이다. 당신은  `#include' C전처리기로 헤더파일 사용을 요청한다.

Uses of Header Files

Header files serve two kinds of purposes.

헤더 파일들은 두가지 목적으로 제공된다.

Including a header file produces the same results in C compilation as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled. The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program.

각 소스 파일로 헤더 파일을 복사하는 것과 헤더파일을 포함시키는 것은 C 컴파일에서 같은 결과를 만든다. 그와 같이 복사는 시간을 낭비할 것이고 error-prone일 것이다. 헤더 파일에서, 관계가 있는 선언들은 단지 하나의 장소에 나타난다. 만약 그것의 수정이 필요 하다면,  한 곳에서 수정 할 수 있고  자동적으로 헤더 파일을 포함한 프로그램들은 다음에 다시 컴파일을 할 때 새로운 버전을 사용한다. 헤더 파일은 코드 복사로 인한 프로그램 내에서의  불일치를 찾지 못하는  위험뿐만 아니라 모든 문서들을 찾아내고 수정해야 하는  노동을 없애 준다.,

The usual convention is to give header files names that end with `.h'. Avoid unusual characters in header file names, as they reduce portability.

일반적인 규정은 헤더 파일들 이름들의 끝을 ' .h'  하는 것이다. 문자가 있는 헤더 파일 이름들에 이상한 문자들을 피하라!.  그들은 가용성을 격하시킨다.

 

The `#include' Directive

Both user and system header files are included using the preprocessing directive `#include'. It has three variants:

사용자와 시스템 헤더 파일들 모두  '#include' 전처리기를 이용해서 포함시킨다. 세가지 변형이 있다.

#include <file>
This variant is used for system header files. It searches for a file named file in a list of directories specified by you, then in a standard list of system directories. You specify directories to search for header files with the command option `-I' (see section Invoking the C Preprocessor). The option `-nostdinc' inhibits searching the standard system directories; in this case only the directories you specify are searched. The first `>' character terminates the file name. The file name may contain a `<' character.

        이 변형은 시스템 헤더 파일들에  쓴다. file이란 이름의 파일은 당신의 특별한 디렉토리에 리스트에서 찾은 다음 일반적인 시스템 디렉토리에서 찾는다. 당신은 명령 옵션 `-I'로 해더파일들을 찾기 위한 디렉토리를 명시 할 수 있다. `-nostdinc' 옵션은 일반적인 시스템 디렉토리들을 검색하는 것을 방지한다; 이  경우 당신이 명시한 디렉토리들에서만 검색한다.

 
 
#include "file"
This variant is used for header files of your own program. It searches for a file named file first in the current directory, then in the same directories used for system header files. The current directory is the directory of the current input file. It is tried first because it is presumed to be the location of the files that the current input file refers to. (If the `-I-' option is used, the special treatment of the current directory is inhibited. See section Invoking the C Preprocessor.) The first `"' character terminates the file name. In both these variants, the argument behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, in `#include <x/*y>' the `/*' does not start a comment and the directive specifies inclusion of a system header file named `x/*y'. However, in either variant, if backslashes occur within file, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus, `#include "x\n\\y"' specifies a filename containing three backslashes.

이 변형은 당신 자신의 프로그램의 헤더 파일들을 위해서 사용된다. 파일이 file이라고 불리었기 현재 디렉토리가 먼저 탐색되고 그 다음에 시스템 헤더 파일들을 위해서 사용되는  디렉토리들을 탐색한다. 현재 디렉토리는 현재 입력 파일의 디렉토리이다. 현재 입력파일로 여겨지는 파일의 위치로 가정 되기 때문에 먼저 시도 된다.( 만약 -I- 옵션이 사용된다면, 현재 디렉토리의 특별한 처리가 금지된다. Invoking the C Preprocessor를 봐라)

먼저 ` " '문자는 파일 이름을 끝을 나타낸다. 이런 두 변형들에서, 인자는 주석에서 문자열 상수가 인식되지 않는 것처럼 행동 한다.

게다가' #include<x /* y> ' 에서  /* 은 주석을 시작을 나타내지 않고  ' x /* y'로 불려지는 헤더파일 이름을 내포하는 지시문으로 구체화된다. .

그러나, 만약 백슬래시들이 파일의 안쪽에 나타나면 어느 변형에서도, 그들은 확장 문자들이 아니라 통상 텍스트 문자들로 생각된다. C에 탈출 문자상수로 적합한 것이 없다. 이처럼, 3개의 백슬래시를 담고 있는 파일 이름을 ' #include " x\n\\y " '로 지정한다.

 
#include anything else
This variant is called a computed #include. Any `#include' directive whose argument does not fit the above two forms is a computed include. The text anything else is checked for macro calls, which are expanded (see section Macros). When this is done, the result must match one of the above two variants -- in particular, the expansion must form a string literal token, or a sequence of tokens surrounded by angle braces. See section Implementation-defined Behavior and Implementation Limits. This feature allows you to define a macro which controls the file name to be used at a later point in the program. One application of this is to allow a site-specific configuration file for your program to specify the names of the system include files to be used. This can help in porting the program to various operating systems in which the necessary system header files are found in different places.

이 변형은 계산된 #include로 불린다. 인자가 위의2가지 인자 형식에 맞지 않는 어떠한 '#include' 지시문도 계산된 include이다. 텍스트 그밖에 무엇이든지 매크로 호출을 위해 확인된다. 그 호출은 확장된다.( see section Macros). 이것이 쓰여질 때 결과는 특히 위에 2가지의 변형중의 하나와 어울려야 한다. - 특히, 확장은 문자열 상수 징표를 형성시키거나, 또는 angle braces로 둘러싸인 토큰들의 열로 형성해야 한다. See section Implementation-defined Behavior and Implementation Limits. 이 특징은 당신이 프로그램에서 조금 더 늦게 사용된 파일 이름을 제어하는 매크로를 규정하도록 허용한다.

이런 애플리케이션은 당신 프로그램이 사용된 파일들을 포함하는 시스템의 이름을 지정하도록 site-specific configuration파일을 허용한다. 이것은 다른 장소들에서 필요한 시스템 헤더 파일들을 찾는 여러 가지 운영체제에 프로그램 이식을 도울 수 있다.

How `#include' Works

The `#include' directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the `#include' directive. For example, given a header file `header.h' as follows,

#include 지시문은 현재 파일의 여분으로 계속 되기 전에 입력으로써 특정한 파일을 검색하는 C 전처리기를 관리하는 것에 의해 작동한다. 전처리기로에 출력은 include된 파일에서 출력의 결과 (#include 지시문 후에 텍스트로부터 일어난 출력에 의해서)에 따라 이미 만들어진 출력을 갖는다.    예를 들면, 다음과 같이 헤더 파일 'header.h'을 주어집니다, .

char *test ();

and a main program called `program.c' that uses the header file, like this,

그리고 main프로그램은 아래와 같은 해더 파일을 사용하는 `program.c' 이다

int x;
#include "header.h"

main ()
{
  printf (test ());
}

the output generated by the C preprocessor for `program.c' as input would be

int x;
char *test ();

main ()
{
  printf (test ());
}

Included files are not limited to declarations and macro definitions; those are merely the typical uses. Any fragment of a C program can be included from another file. The include file could even contain the beginning of a statement that is concluded in the containing file, or the end of a statement that was started in the including file. However, a comment or a string or character constant may not start in the included file and finish in the including file. An unterminated comment, string constant or character constant in an included file is considered to end (with an error message) at the end of the file.

포함된 파일들은 선언들 그리고 매크로 정의에 제한되지 않는다; 저것들은 단지 전형적인 사용이다.  C 프로그램의 어떠한 fragment라도 또 다른 파일로부터 include 될 수 있다. include파일은 담고 있는 파일에 결말 부의 시작 또는 including파일의 시작 끝에 포함 될 수 있다. 그러나 주석이나 문자열 또는 문자 상수는 including 파일의 시작이나 끝이 아닐 것이다. including 파일에 마쳐지지 않은 주석, 문자열 상수, 문자 상수는 (에러 메시지와 함께) 파일의 끝에 끝으로 생각되어 진다.

It is possible for a header file to begin or end a syntactic unit such as a function definition, but that would be very confusing, so don't do it.

헤더 파일은 함수 정의와 같은 구문적인 장치를 시작하거나 끝내는 것은 가능하지만 그것은 매우 혼란스러울 것이다. 그래서 그렇게 하지 않는다.

The line following the `#include' directive is always treated as a separate line by the C preprocessor, even if the included file lacks a final newline.

`#include' 지시문 다음에 라인은 included된 파일에 마지막 newline이 부족 해도 항상 C 전처리기에 의해 분리된 라인으로써 다루어 진다.

Once-Only Include Files

Very often, one header file includes another. It can easily result that a certain header file is included more than once. This may lead to errors, if the header file defines structure types or typedefs, and is certainly wasteful. Therefore, we often wish to prevent multiple inclusion of a header file.

매우 자주, 1개의 헤더 파일은 다른 헤더 파일을 포함한다.어떤 헤더 파일이 여러 번에 걸쳐 포함되는 것은 쉽게 발생 할 수 있다. 만약 헤더 파일이 구조 형들 또는 typedefs를 규정하면 이것은 에러를 초래하고  비경제적이다.그러므로, 우리들 자주 헤더 파일의 다중 내포를 막는 것을 원한다.

The standard way to do this is to enclose the entire real contents of the file in a conditional, like this:

이것을 할 표준 방법은 이것처럼 조건어구에 파일의 전체 실제내용들을 둘러싸는 것이다:

#ifndef FILE_FOO_SEEN
#define FILE_FOO_SEEN

the entire file

#endif /* FILE_FOO_SEEN */

The macro FILE_FOO_SEEN indicates that the file has been included once already. In a user header file, the macro name should not begin with `_'. In a system header file, this name should begin with `__' to avoid conflicts with user programs. In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.

매크로 FILE_FOO_SEEN은 파일이 한 번 이미 포함되었던 것을 나타낸다.사용자 헤더 파일에, 매크로 이름은 ' _'로 시작하지 않아야 한다. 시스템 헤더 파일에, 이 이름은 사용자 프로그램들과 충돌들을 피하기 위하여 '__'을 가지고 시작하여야만 한다. 어떤 종류의 헤더파일에서, 매크고 이름은 다른 헤더 파일들과 충돌들을 피하기 위하여 파일과 몇몇 추가적인 텍스트의 이름을 포함하여야만 한다.

The GNU C preprocessor is programmed to notice when a header file uses this particular construct and handle it efficiently. If a header file is contained entirely in a `#ifndef' conditional, modulo whitespace and comments, then it remembers that fact. If a subsequent `#include' specifies the same file, and the macro in the `#ifndef' is already defined, then the directive is skipped without processing the specified file at all.

헤더 파일이 특별한 구조를 사용하고 그것을 효율적을 다룰 때를 알 수 있도록 GNU C 전처리기는 프로그램 되어 있다. 만약 헤더 파일이 `#ifndef' 조건 어구에 전체적으로 포함되어 있으면 공백과 주석을 규칙으로 해서 그것은 사실로 기억 된다. 만약 `#include'이 같은 파일을 지정하고 `#ifndef'에 매크로는 이미 정의 되어 있으면 지시문은 지정된 파일 모두를 처리하지 않고 건너뛰어 진다.

In the Objective C language, there is a variant of `#include' called `#import' which includes a file, but does so at most once. If you use `#import' instead of `#include', then you don't need the conditionals inside the header file to prevent multiple execution of the contents.

Objective 씨 언어에는 파일을 포함하지만  최대한 한번만 포함하는 '#import'로 불려지는 '#include'의 변형은 있다. 만약 당신이 '#include'대신에 '#import'을 사용한다면, 당신은 내용들의 다중 실행을 방지하기 위한 헤더 파일 안에 조건 어구들이 필요하지 않다.

`#import' is obsolete because it is not a well designed feature. It requires the users of a header file -- the applications programmers --- to know that a certain header file should only be included once. It is much better for the header file's implementor to write the file so that users don't need to know this. Using `#ifndef' accomplishes this goal.

'#import'은 잘 설계된 형태가 아니기 때문에 쓸모 없다. 그것은 어떤 헤더 파일 오직 한 번 포함되어야 하다는 것을 알고 있는  사용자들을 요구한다 --응용 프로그래머들  --- 헤더 파일의 작성자가 사용자들이 이것을 아는 것이 필요하지 않도록 파일에 기록하는 것은 훨씬 더 좋다. '#ifndef'을 사용함으로써 이 목표를 달성한다.

Inheritance and Header Files

Inheritance is what happens when one object or file derives some of its contents by virtual copying from another object or file. In the case of C header files, inheritance means that one header file includes another header file and then replaces or adds something.

상속은  어떤 객체 또는 파일이 다른 객체나 파일로부터 가상적인 복사에 의해 파생되어 질 때 일어나는 것이다. C 헤더 파일들의 경우, 상속은 한 헤더파일이 다른 헤더파일을 포함하고 그 후에 대체되거나 무언가 더해지는 것을 의미한다.

If the inheriting header file and the base header file have different names, then inheritance is straightforward: simply write `#include "base"' in the inheriting file.

만약 상속된 헤더 파일과 베이스 헤더 파일이 다른 이름들을 갖고 있다면, 상속은 직선적이다.:  간단하게 상속 받는 파일에 `#include "base" '로 쓴다.

Sometimes it is necessary to give the inheriting file the same name as the base file. This is less straightforward.

때때로 베이스 파일과 같은 이름을 상속한 파일에 주는 것이 필요한다. 이것은 덜 직선적이다.

For example, suppose an application program uses the system header `sys/signal.h', but the version of `/usr/include/sys/signal.h' on a particular system doesn't do what the application program expects. It might be convenient to define a "local" version, perhaps under the name `/usr/local/include/sys/signal.h', to override or add to the one supplied by the system.

예를 들면, 응용 프로그램이 시스템 헤더 파일 ' sys/signal.h'를 사용한다고 생각해 보자. 그러나 특별한 시스템에 '/usr/include/sys/signal.h'의 버전은 응용 프로그램이 기대한 것을 하지 않는다. 아마도 /usr/local/include/sys/signal.h' 이름으로 시스템에 의해서 공급된 것을 오버라이드하거나  증가시키기 위하여 지역 버전을 규정하는 것이 편리할 것이다.

You can do this by compiling with the option `-I.', and writing a file `sys/signal.h' that does what the application program expects. Making this file include the standard `sys/signal.h' is not so easy --- writing `#include <sys/signal.h>' in that file doesn't work, because it includes your own version of the file, not the standard system version. Used in that file itself, this leads to an infinite recursion and a fatal error in compilation.

당신은 ' -I.'옵션으로 컴파일함으로써 이것을 할 수 있다.그리고 응용 프로그램이 기대하는 것을 하는 'sys/signal.h'를 쓸 수 있다. 표준 'sys/signal.h'을 포함하는 파일을 만드는 것은 그렇게 쉽지 않다  -- 표준 시스템 버전이 아니라 당신의 파일 버전이기 때문에 `#include <sys/signal.h>'는 작동하지 않는다. Used in that file itself, 이것은 무한 재귀호출과 치명적인 컴파일 에러를 초래 한다.

`#include </usr/include/sys/signal.h>' would find the proper file, but that is not clean, since it makes an assumption about where the system header file is found. This is bad for maintenance, since it means that any change in where the system's header files are kept requires a change somewhere else.

' #include</usr/include/sys/signal.h>는 적당한 파일을 발견할 것이다. 그러나 시스템 헤더 파일이 발견되는 곳을 가정하기 때문에 그것은 깨끗하지 않다. 보존되는 시스템 헤더파일에 어떠한 변화도 다른 곳에서의 변화를 요구하기 때문에 이것은 유지보수에 나쁘다..

The clean way to solve this problem is to use `#include_next', which means, "Include the next file with this name." This directive works like `#include' except in searching for the specified file: it starts searching the list of header file directories after the directory in which the current file was found.

이 문제를 해결할 깔끔한(^^;) 방법은 '#include_next'을 사용하는 이다.                                         이 '#include_next'은  "이 이름으로 next 파일을 포함해라" 라는 것을 의미한다. 이 지시문은 특정한 파일을 찾는 것을 제외하고 '#include'처럼 작동한다 : 현재 파일이 발견되었던 디렉토리 다음에 헤더 파일 디렉토리들의 리스트의 탐색을 시작한다.

Suppose you specify `-I /usr/local/include', and the list of directories to search also includes `/usr/include'; and suppose both directories contain `sys/signal.h'. Ordinary `#include <sys/signal.h>' finds the file under `/usr/local/include'. If that file contains `#include_next <sys/signal.h>', it starts searching after that directory, and finds the file in `/usr/include'.

당신이 `-I /usr/local/include'를 지정하고, 찾기 위한 디렉토리 리스트는 `/usr/include'를 포함한다고 가정하자: 그리고 `sys/signal.h'를 담고 있는 디렉토리도 가정하자. 일반적으로 `#include <sys/signal.h>'는 `/usr/local/include'아래서 찾는다. 만약 그 파일이`#include_next <sys/signal.h>'를 포함하고 있다면 그 디렉토리 다음에 탐색을 시작하고 `/usr/include'에서 파일을 찾는다.

`#include_next' is a GCC extension and should not be used in programs intended to be portable to other compilers.

'#include_next'은 GCC 확장이고 다른 컴파일러들에 싣도록 된 프로그램들에 사용되지 않아야 한다.

System Headers

The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore, GNU C gives code found in system headers special treatment. Certain categories of warnings are suppressed, notably those enabled by `-pedantic'.

운영체제와 런타임 라이브러리들에 인터페이스로 선언된 헤더 파일들은 엄밀하게 C에 따르도록 쓰여지지 않는다. 그래서 GNU C는 특별하게 다루어진 시스템 파일들에 코드를 제공 한다. 어떤 종류의 경고들은  `-pedantic'로 확실하게 억제 되어진다.

Normally, only the headers found in specific directories are considered system headers. The set of these directories is determined when GCC is compiled. There are, however, two ways to add to the set.

일반적으로 특정 디렉토리들에서만 발견되는 헤더들은 시스템 헤더들로 생각된다.이 디렉토리들의 집합은  GCC로 컴파일 될 때 결정되어진다. 그러나, 2가지 방법을 이 집합에 더했다.

The `-isystem' command line option adds its argument to the list of directories to search for headers, just like `-I'. In addition, any headers found in that directory will be considered system headers. Note that unlike `-I', you must put a space between `-isystem' and its argument.

`-isystem' 명령 라인 옵션은 헤더들을 찾기 위하여 디렉토리들의 리스트에 그것의 인자를 더한다.  `-l' 옵션과 같다. 덧붙여 말하자면, 어떤 헤더들도 시스템 헤더들로 생각되는 디렉토리에서 찾는다. 주의 할 것은 '-I'와는 달리, 당신은 '-isystem'와 그것의 인자사이에 공간을 놓아야만 한다는 것이다..

All directories named by `-isystem' are searched after all directories named by `-I', no matter what their order was on the command line. If the same directory is named by both `-I' and `-isystem', `-I' wins; it is as if the `-isystem' option had never been specified at all.

명령 라인에 그들의 순서가 무엇이든지 `-I'에 의해 불린 모든 디렉토리의 탐색 후에 '-isystem'에 의해 불린 모든 디렉토리들이 탐색 된다. 만약  `-I' 과`-isystem' 모두 디렉토리 이름이 같으면 `-I'가 우선이다; `-isystem' 옵션은 결코 지정되지 않는 것과 마찬가지다.

There is also a directive, `#pragma GCC system_header', which tells GCC to consider the rest of the current include file a system header, no matter where it was found. Code that comes before the `#pragma' in the file will not be affected.

어디서 찾아지든 현재include 시스템 헤더 파일의 나머지를 GCC로 여기는 `#pragma GCC system_header' 지시문 또한 있다. 파일에서 `#pragma' 이전에 오는 코드는 영향 받지 않을 것이다.

`#pragma GCC system_header' has no effect in the primary source file.

`#pragma GCC system_header'는 초기 소스에 효력이 없다.

Macros

A macro is a sort of abbreviation which you can define once and then use later. There are many complicated features associated with macros in the C preprocessor.

매크로는 한 번 정의를 내릴 수 있고 그 다음에 나중에 사용하는 abbreviation 종류이다. C 전처리기에는 매크로와 연관된 복잡한 특징이 많이 있다.

Object-like Macros

An object-like macro is a kind of abbreviation. It is a name which stands for a fragment of code. Some people refer to these as manifest constants.

object-like macro는 abbreviation의 일종이다. 그것은 코드 조각을 나타내는 이름이다. 어떤 사람들은  명백한 상수들로서 이것들을 생각한다.

Before you can use a macro, you must define it explicitly with the `#define' directive. `#define' is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,

당신이 매크로를 사용할 수 있기 전에는  명시적으로 `#define' 지시문과 함께 정의 해야만 한다. `#define' 다음에는 매크로의 이름이 따른다. 그 다음에는 매크로의 몸체, 확장 또는 교체할 리스트로써 abbreviation 되어야 하는 토큰 열이 온다.

#define BUFFER_SIZE 1020

defines a macro named `BUFFER_SIZE' as an abbreviation for the token `1020'. If somewhere after this `#define' directive there comes a C statement of the form

`BUFFER_SIZE'는 `1020' 토큰에 abbreviation로 이름 지어진 매크로로 정의 된다. 이 `#define'지시문 후에 어디에서 그 형식의 C서술이 오면,

foo = (char *) xmalloc (BUFFER_SIZE);

then the C preprocessor will recognize and expand the macro `BUFFER_SIZE', resulting in

그 다음에 C 전처리기는 안에 결과로서 생긴 매크로 'BUFFER_SIZE'를 인식할 것이고  확장할 것이다.

foo = (char *) xmalloc (1020);

The use of all upper case for macro names is a standard convention. Programs are easier to read when it is possible to tell at a glance which names are macros.

매크고 이름들을 위한 대문자 사용은 일반적인 관례이다. 프로그램들은 매크로 이름들을 흘긋 보는 거시 가능할 때 읽기 쉽다.

Normally, a macro definition can only span a single logical line, like all C preprocessing directives. Comments within a macro definition may contain newlines, which make no difference since each comment is replaced by a space regardless of its contents.

일반적으로, 매크로 정의는 모든 C전처리 지시문처럼 하나의 논리 라인으로만 놓일 수 있다. 매크로 내에서 주석들은 newline들로 포함 될지 모른다. 그러나 각 주석이 그것의 내용에 상관 없는 공간으로 대체 되기 때문에 차이점이 없다.

Apart from this, there is no restriction on what can go in a macro body provided it decomposes into valid preprocessing tokens. In particular, parentheses need not balance, and the body need not resemble valid C code. (If it does not, you may get error messages from the C compiler when you use the macro.)

이것과는 별개로, 올바른 전처리 토큰들로 분해하도록 제공된 매크로 body로 갈 수 있는 것에는 제한이 없다. 특히 괄호들은 균형이 필요 없고 몸체는 올바른C코드와 닮을 필요는 없다.(그렇지 않으면 당신이 매크로를 이용할 때 C 컴파일러로부터 에러 메시지를 받게 될 지 모른다.)

The C preprocessor scans your program sequentially, so macro definitions take effect at the place you write them. Therefore, the following input to the C preprocessor

전처리기는 연속적으로 당신의 프로그램을 검색한다. 그래서 당신이 매크로를 쓴 곳에서  매크로 정의가 효과가 있게 한다. 그러므로, C 전처리기에 입력이 뒤 따른다.

foo = X;
#define X 4
bar = X;

produces as output

출력을 만든다.

foo = X;

bar = 4;

When the preprocessor expands a macro name, the macro's expansion replaces the macro invocation, and the result is re-scanned for more macros to expand. For example, after

전처리기가 매크로 이름을 확장할 때, 매크로의 확장은 매크로 호출을 바꾼다. 그리고 결과는 다시 매크로 확장을 위해 다시 검색된다. 예를 들면,

#define BUFSIZE 1020
#define TABLESIZE BUFSIZE

the name `TABLESIZE' when used in the program would go through two stages of expansion, resulting ultimately in `1020'.

`TABLESIZE' 이름이 프로그램에서 사용 될 때 두가지 확장 스테이지를 통과하고 마침내 `1020’란 결과가 나온다.

This is not the same as defining `TABLESIZE' to be `1020'. The `#define' for `TABLESIZE' uses exactly the expansion you specify -- in this case, `BUFSIZE' -- and does not check to see whether it too contains macro names. Only when you use `TABLESIZE' is the result of its expansion scanned for more macro names. See section Cascaded Use of Macros.

이것은 `1020'가 `TABLESIZE'로 정의 되는 것과 같지 않다. `TABLESIZE'를 위한  `#define'는 정확하게 당신이 지정한 확장을 이용된다.이 경우에는 `BUFSIZE'이다 그리고 매크로 이름들을 포함했는지 않았는지를 보기 위해서 체크하지는 않는다.

Macros with Arguments

An object-like macro is always replaced by exactly the same tokens each time it is used. Macros can be made more flexible by taking arguments. Arguments are fragments of code that you supply each time the macro is used. These fragments are included in the expansion of the macro according to the directions in the macro definition. A macro that accepts arguments is called a function-like macro because the syntax for using it looks like a function call.

object-like 매크로는  정확하게 매번 같은 토큰들로 항상 대체 된다. 매크로는 인자들을 좀 더 유연하게 받아 들일 수 있다. 인자들은 당신이 매크로가 이용 될 때 마다 제공 되는 코드의 조각들이다. 이 조각들은 매크로 정의에 방향을 따라 매크로 확장에 포함 된다. 인자를 받아들이는 매크로는 function-like 매크로로 불리는데 그것을 사용하는 문법이 함수 호출과 같이 보이기 때문이다.

To define a macro that uses arguments, you write a `#define' directive with a list of parameters in parentheses after the name of the macro. The parameters must be valid C identifiers, separated by commas and optionally whitespace. The `(' must follow the macro name immediately, with no space in between. If you leave a space, you instead define an object-like macro whose expansion begins with a `(', and often leads to confusing errors at compile time.

인자를 이용하는 매크로를 정의 하기 위해서 당신은  매크로 이름 뒤에 괄호로 파라미터의 리스트를 지정해서 `#define'를 쓴다. 파라미터들은 콤마와 선택적인 공백으로 분리된 올바른 C 식별자여야만 한다. `('는 공간 없이 매크로 이름 뒤에 바로 와야 한다. 만약 공간이 남으면, 대신에 당신은 `(' 로 시작하는 object-like 매크로를 정의하게 된고 컴파일 시 복잡한 에러를 자주 초래하게 된다.

As an example, here is a macro that computes the minimum of two numeric values, as it is defined in many C programs:

한 예로, 많은 C 프로그램들에서 정의 되는 두 개의 숫자 값에서 작은 값을 계산하는 매크로가 있다.

#define min(X, Y)  ((X) < (Y) ? (X) : (Y))

(This is not the best way to define a "minimum" macro in GNU C. See section Duplication of Side Effects, for more information.)

( 이것은 GNU C에서 "minimum" 매크로를 정의 하는 제일 좋은 방법은 아니다. 더 많은 정보를 위해 Duplication of Side Effects 부분을 봐라. ) .

To invoke a function-like macro, you write the name of the macro followed by a list of arguments in parentheses, separated by commas. The invocation of the macro need not be restricted to a single logical line - it can cross as many lines in the source file as you wish. The number of arguments you give must match the number of parameters in the macro definition; empty arguments are fine. Examples of use of the macro `min' include `min (1, 2)' and `min (x + 28, *p)'.

function-like 매크로를 호출하기 위해서 당신은 매크로 이름 위에 괄호에 콤마로 분리된 인자들의 리스트가 오도록 매크로를 쓴다. 매크로 호출은 하나의 논리적 라인으로 제한 될 필요는 없다.- 그것은 당신이 원하는 만큼 소스 파일에 많은 라인으로 놓을 수 있다. 당신은 인자들의 수를 매크로 정의에서의 파라미터의 수와 일치 시켜야 한다; 빈 인자들은 괜찮다. `min' 매크로의 예로 `min (1, 2)'과 `min (x + 28, *p)'를 포함한다.

The expansion text of the macro depends on the arguments you use. Each macro parameter is replaced throughout the macro expansion with the tokens of the corresponding argument. Leading and trailing argument whitespace is dropped, and all whitespace between the tokens of an argument is reduced to a single space. Using the same macro `min' defined above, `min (1, 2)' expands into

매크로의 확장 텍스트는 당신이 사용하는 인자에 의존한다. 각 매크로 파라미터는 일치하는 인자의 토큰으로 매크로 확장을 통해 대체 된다. 처음과 마지막 인자 공백은 제거 되고 인자의 토큰 사이의 모든 공백은 하나의 공간으로 줄어든다. 위에서 정의된  `min'같은 매크로를 이용해서, `min (1, 2)'로 확장하면,

((1) < (2) ? (1) : (2))

where `1' has been substituted for `X' and `2' for `Y'.

`1'은 `X'에서 대체 되었고 `2'는 `Y'에서 대체 됬다.

Likewise, `min (x + 28, *p)' expands into

비슷하게 `min (x + 28, *p)'도 확장 된다

((x + 28) < (*p) ? (x + 28) : (*p))

Parentheses within each argument must balance; a comma within such parentheses does not end the argument. However, there is no requirement for square brackets or braces to balance, and they do not prevent a comma from separating arguments. Thus,

각 인자 내에서 괄호는 균형 맞게 쓰여야만 한다; 그런 괄호 내에서 콤마는 인자의 끝이 아니다. 그러나, 균형을 위해 square brackets 또는 braces는 필요 없고 분리된 인자로부터 콤마를 막지 않는다. 게다가,

macro (array[x = y, x + 1])

passes two arguments to macro: `array[x = y' and `x + 1]'. If you want to supply `array[x = y, x + 1]' as an argument, you must write it as `array[(x = y, x + 1)]', which is equivalent C code.

매크로에서 두개의 인자들을 통과 시킨다: `array[x = y' and `x + 1]’. 만약 당신이 인자로써 `array[x = y, x + 1]'를 제공한다면 C 코드와 같게 `array[(x = y, x + 1)]'을 써야만 한다.

After the arguments have been substituted into the macro body, the resulting expansion replaces the macro invocation, and re-scanned for more macro calls. Therefore even arguments can contain calls to other macros, either with or without arguments, and even to the same macro. For example, `min (min (a, b), c)' expands into this text:

인자가 매크로 body로 대체된 후에, 결과확장은 매크로 호출로 대체 되고 더 많은 매크로 호출을 위해 다시 검색 된다. 그러므로 인자가 없든지 있든지, 인자들은 다른 매크로들의 호출을 포함 할 수 있고 같은 매크로 조차 포함 할 수 있다. 예를 들면 ,

((((a) < (b) ? (a) : (b))) < (c)
 ? (((a) < (b) ? (a) : (b)))
 : (c))

(Line breaks shown here for clarity would not actually be generated.)

(명료하게 나타내기 위해 여기에 보여진 Line breakes들은 실제로 만들어지지 않을 것이다 )

If a macro foo takes one argument, and you want to supply an empty argument, simply supply no preprocessing tokens. Since whitespace does not form a preprocessing token, it is optional. For example, `foo ()', `foo ( )' and `bar (, arg2)'.

만약 foo가 하나의 인자를 받아 들이고 당신이 인자가 는 것을 제공하기를 위한 다면 전처리 토큰 없이 간단하게 제공 할 수 있다. 공백은 전처리 토큰이 아니기 때문에, 그것은 선택이다. 예를 들면 `foo()', `foo()' 그리고 `bar(, arg2)'.  

Previous GNU preprocessor implementations and documentation were incorrect on this point, insisting that a function-like macro that takes a single argument be passed a space if an empty argument was required.

매크로가 인자가 없는 것을 요구하면 하나의 인자를 받아들이는 function-like는 공간으로 지나쳐 진다는 주장할 때, 먼저 GNU 전처리의 수행과 문서화는 이 점에서 부정확하다.

If you use a macro name followed by something other than a `(' (after ignoring any whitespace that might follow), it does not form an invocation of the macro, and the preprocessor does not change what you have written. Therefore, it is possible for the same identifier to be a variable or function in your program as well as a macro, and you can choose in each instance whether to refer to the macro (if an actual argument list follows) or the variable or function (if an argument list does not follow). For example,

만약 (뒤따라올 어떤 공백도 무시한 후에) `(' 보다 다른 무언가가  오는 매크로 이름을 사용한다면, 그것은 매크로 호출의 형식이 아니고 전처리기는 당신이 쓰는 것을 바꾸지 않는다. 그러므로 매크로 와 마찬가지로  같은 식별자가 당신의 프로그램에 변수와 함수가 되는 것이 가능 하다. 그리고 당신은 매크로(실제로 인자리스트가 뒤따라 오면)든지 변수든지 함수( 인자리스트가 뒤따라오지 않으면)든지 각 인스턴스들을 고를 수 있다.

#define foo(X) X
foo bar foo(baz)

expands to `foo bar baz'. Such dual use of one name could be confusing and should be avoided except when the two meanings are effectively synonymous: that is, when the name is both a macro and a function and the two have similar effects. You can think of the name simply as a function; use of the name for purposes other than calling it (such as, to take the address) will refer to the function, while calls will expand the macro and generate better but equivalent code.

`foo bar baz'로 확장했다. 이런 하나의 이름의 두 가지 사용은 복잡할 수 있다. 그리고 효과적으로 두 가지 의미가 같게 하려고 할 때를 제외하고는 피해야만 한다.:즉 함수와 매크로 두가지가 비슷한 효과를 가질 때. 당신은 간단한 이름을 함수로 생각 할 수 있다; 함수를 호출하는 것보다 다른 목적(주소를 받기 위해)의 이름을 사용하는 것은 호출이 매크로를 확장하고 같은 코드를 제외하고 더 낫게 생성할 함수로 생각 될 것이다.

For example, you can use a function named `min' in the same source file that defines the macro. If you write `&min' with no argument list, you refer to the function. If you write `min (x, bb)', with an argument list, the macro is expanded. If you write `(min) (a, bb)', where the name `min' is not followed by an open-parenthesis, the macro is not expanded, so you wind up with a call to the function `min'.

예를 들면, 당신은 매크로로 정의한 `min'이라는 이름을 같은 소스에서 함수로 사용할 수 있다. 만약 인자 리스트 없이 `&min' 를 쓰면 당신은 함수로  생각한다. 만약 `min (x, bb)'를 쓰면, 매크로는 확장 된다. 만약 당신이  `(min) (a, bb)'를 쓰고 `min' 뒤에 열린 괄호가 없으면 매크로는 확장되지 않는다. 그래서 당신은 함수 `min’을 호출하기 위해 마지막 손질을 한다.

In the definition of a macro with arguments, the list of argument names must follow the macro name immediately with no space in between. If there is a space after the macro name, the macro is defined as taking no arguments, and all the rest of the line is taken to be the expansion. The reason for this is that it is often useful to define a macro that takes no arguments and whose definition begins with an identifier in parentheses. This rule makes it possible for you to do either this:

인자가 있는 매크로에서 인자 이름 리스트는 공간 없이 매크로 이름 뒤에 바로 와야 한다. 만약 매크로 이름 뒤에 공간이 있으면 매크로는 인자를  받아들이지 않는 것으로 정의 된다. 그리고 모든 라인의 나머지는 확장이 된다. 이유는 인자 없이 매크로가 정의되고 괄호에 식별자로 시작하는 매크로의 정의는 자주 유용하기 때문이다.

#define FOO(x) - 1 / (x)

(which defines `FOO' to take an argument and expand into minus the reciprocal of that argument) or this:

(`F00'는 인자를 받아 들이고 음수인 역수로 확장되도록 정의된다.)

#define BAR (x) - 1 / (x)

(which defines `BAR' to take no argument and always expand into `(x) - 1 / (x)').

( `BAR'는 인자가 없고 항상 into `(x) - 1 / (x)'로 확장된다)

Note that the uses of a macro with arguments can have spaces before the left parenthesis; it's the definition where it matters whether there is a space.

인자들이 있는 매크로를 사용하는 것은 왼쪽 괄호 전에 공간들을 가질 수 있다는 것에 주의 해라; 그것은 공간이 있던지 없던지 정의이다.

Macros with Variable Numbers of Arguments

이 섹션은 전체적을 해석 다시 해야함.

In the ISO C standard of 1999, a macro can be declared to accept a variable number of arguments much as a function can. The syntax for defining the macro is similar to that of a function. Here is an example:

1999년ISO C에서는 매크로가 함수처럼 많은 가변 숫자를 인자로 받아 드릴 수 있도록 선언 될 수 있다. 매크로 정의 문법은 함수와 비슷하다. 여기 예가 있다.

#define eprintf(...) fprintf (stderr, __VA_ARGS__)

Here `...' is a variable argument. In the invocation of such a macro, it represents the zero or more tokens until the closing parenthesis that ends the invocation, including any commas. This set of tokens replaces the identifier __VA_ARGS__ in the macro body wherever it appears. Thus, we have this expansion:

`...'은 가변 인자이다. 이런 매크로의 호출에서 호출을 마치는 괄호를 닫을 때 까지 어떤 콤마도 포함하면서0 또는 더 많은 토큰들을 표현한다. 이 토큰 설정은 매크로 body에 __VA_ARGS__가 나타나는 어디든지 대체된다. 게다가 우리는 이것을 확장을 가지고 있다.

eprintf ("%s:%d: ", input_file_name, line_number)
==>
fprintf (stderr, "%s:%d: " , input_file_name, line_number)

Within a `#define' directive, ISO C mandates that the only place the identifier __VA_ARGS__ can appear is in the replacement list of a variable-argument macro. It may not be used as a macro name, macro argument name, or within a different type of macro. It may also be forbidden in open text; the standard is ambiguous. We recommend you avoid using it except for its defined purpose.

<해석 잘 안됨>

`#define' 지시문 내에서, __VA_ARGS__ 식별자가 나타날 수 있는 곳에서의 ISO C 명령들은 가변 인자 매크로 교체 리스트 이다. 매크로 이름, 매크로 인자 이름으로써 사용 되지 않을 것이다. 또한 열린 텍스트에서 금지 될 것이다. 우리는 당신이 정의 된 목적 이외의 사용을 피하기를 권장한다.

If your macro is complicated, you may want a more descriptive name for the variable argument than __VA_ARGS__. GNU cpp permits this, as an extension. You may write an argument name immediately before the `...'; that name is used for the variable argument. The eprintf macro above could be written

만약 당신의 매크로가 복잡해지면, 당신은 __VA_ARGS__보다 가변 인자를 위해 좀 더 설명적인 이름을 원할 수 있디. GNU cpp는이것이 있는 이것에 확장을 허락한다. 당신은 `...' 전에 바로 인자 이름을 쓸 수 있다; 그 이름은 가변 인자를 위해 사용 된다. eprintf 매크로 위에 쓰여 질 수 있었다.

#define eprintf(args...) fprintf (stderr, args)

using this extension. You cannot use __VA_ARGS__ and this extension in the same macro.

이 확장을 이용한다. 당신은  __VA_ARGS__과  이 확장을 같은 매크로에서 사용 할 수 없다.

We might instead have defined eprintf as follows:

우리는 대신 eprintf를 다음과 같이 정의 해 왔을 것이다.

#define eprintf(format, ...) fprintf (stderr, format, __VA_ARGS__)

This formulation looks more descriptive, but cannot be used as flexibly. There is no way to produce expanded output of

이 공식은 좀더 설명적으로 보이지만 유연하게 쓰일 수 없다. 확장된 출력을 만들 방법이 없다.

fprintf (stderr, "success!\n")

because, in standard C, you are not allowed to leave the variable argument out entirely, and passing an empty argument for the variable arguments will not do what you want. Writing

왜냐하면 표준 C 대신에 당신은 전체적으로 가변 인자들을 남기는 것을 허락하지 않는다. 그리고 가변 인자들로 아무 인자도 넘겨 주지 않으면 당신이 원하는 것을 하지 않을 것이다.

eprintf ("success!\n", )

produces

fprintf (stderr, "success!\n",)

where the extra comma originates from the replacement list and not from the arguments to eprintf.

교체 리스트로부터 여분의 콤마가 만들어 지고 인자들에서부터 eprintf까지는 아니다.

There is another extension in the GNU C preprocessor which deals with this difficulty. First, you are allowed to leave the variable argument out entirely:

GNU C전처리기에서 확장을 다루는 다른 어려움이 있다. 먼저, 당신이 전체적으로 밖의 가변 인자들을 생략하는 것을 허락한다.

eprintf ("success!\n")

Second, the `##' token paste operator has a special meaning when placed between a comma and a variable argument. If you write

두 번째로, `##'토큰은 복사 연산자는 콤마와 가변 인자 사이에 위치할 때 특별한 의미를 갖는다. 만약 당신이 아래와 같이 쓰면

#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)

and the variable argument is left out when the `eprintf' macro is used, then the comma before the `##' will be deleted. This does not happen if you pass an empty argument, nor does it happen if the token preceding `##' is anything other than a comma.

가변 인자는 eprintf 매크로가 사용될 때 생략되고, 그 다음엔 ## 전에 콤마는 삭제될 것이다. 만약 당신이 비어 있는 인자를 넘긴다면 이것은 우연히 나타나지 않고 그것은 만약 '##'을 선행한 토큰이 콤마가 아닌 어떤 것이더라도 발생하지 않는다.

Previous versions of the preprocessor implemented this extension much more generally. We have restricted it in order to minimize the difference from the C standard. See section Undefined Behavior and Deprecated Features.

이전 전처리기 버전들은 좀더 일반적으로 이 확장을 다루 었다. 우리는 C 표준과의 차이점을 최소화하기 위해 그것을 제한해 왔다. Undefined Behavior and Deprecated Features부분을 봐라

 

Predefined Macros

Several object-like macros are predefined; you use them without supplying their definitions. They fall into two classes: standard macros and system-specific macros.

여러 object-like 매크로들은 이미 정의 되어 있다; 당신은 그들의 정의 없이 사용할 수 있다. 그들은 두 가지 부류로 나눈다: 표준 매크로와 시스템 지정 매크로

Standard Predefined Macros

The standard predefined macros are available with the same meanings regardless of the machine or operating system on which you are using GNU C. Their names all start and end with double underscores. Those preceding __GNUC__ in this table are standardized by ISO C; the rest are GNU C extensions.

미리 정의 된 표준 매크로들은 당신이 GNU C를 사용하고  있는 기계 또는 운영체제에 상관 없이 모두 같은 의미로 사용할 수 있다. 그들의 이름은 모든 시작과 끝이 두개의 언더스코어로 되어 있다. __GNUC__가 테이블에서 선행 되면 ISO C에 의해 표준화 된다; 나머지는 GNU C 확장이다.

__FILE__
This macro expands to the name of the current input file, in the form of a C string constant. The precise name returned is the one that was specified in `#include' or as the input file name argument. For example, `"/usr/local/include/myheader.h"' is a possible expansion of this macro.

        이 매크로는 C 문자열 상수의 형식으로 현재 입력 파일의 이름으로 확장 된다. 반환된 정확한 이름은 `#include'에서 지정되거나 입력 파일 이름 인자로써 지정된다.

 
__LINE__
This macro expands to the current input line number, in the form of a decimal integer constant. While we call it a predefined macro, it's a pretty strange macro, since its "definition" changes with each new line of source code. This and `__FILE__' are useful in generating an error message to report an inconsistency detected by the program; the message can state the source line at which the inconsistency was detected. For example,

        이 매크로는 10진 정수의 형태로 현재 입력 라인의 수로 확장 된다. 우리가 미리 정의된 매크로를 호출하는 동안 이것은 꽤 이상한 매크로 이다. 왜냐하면 그것의 "정의"는  소스 코드의 각 새로운 라인으로 바뀌기 때문이다. 이것과 `__FILE__'은 프로그램에서 찾아 지는 불일치를 보고하는 에러 메시지를 만드는데 유용하다; 그 메시지는 일치하지 않는  소스 라인을 찾아서 나타낼 수 있다.

fprintf (stderr, "Internal error: "
                 "negative string length "
                 "%d at %s, line %d.",
         length, __FILE__, __LINE__);
A `#include' directive changes the expansions of `__FILE__' and `__LINE__' to correspond to the included file. At the end of that file, when processing resumes on the input file that contained the `#include' directive, the expansions of `__FILE__' and `__LINE__' revert to the values they had before the `#include' (but `__LINE__' is then incremented by one as processing moves to the line after the `#include'). The expansions of both `__FILE__' and `__LINE__' are altered if a `#line' directive is used. See section Combining Source Files.

'#include' 지시문은 포함된 파일에 부합하기 위하여 '__FILE__' 그리고 '__LINE__'의 확장들을 바꾼다. 그 파일의 끝에서 `#include' 지시문을 담고 있는 입력 파일의 처리가 재개될 때, `__FILE__'과 `__LINE__'확장은  `#include'전에 값들로 복귀된다.(그러나 `__LINE__’은 다음에 `#include’ 뒤에 라인으로 처리가 움직임으로써 하나가 증가 된다). `__FILE__' 과  `__LINE__' 확장 모두 `#line’지시문이 사용되면 바뀐다. Combining Source Files. 부분을 봐라

__DATE__
This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like `"Feb 1 1996"'.

        이 매크로는 전처리기 실행이 시작되는 날짜를 설명하는 문자열 상수로 확장 된다. 문자열 상수는 11개 문자들을 포함하고 `"Feb 1 1996"'과 같다

__TIME__
This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like `"23:59:01"'.

        이 매크로는 전처리기가 실행되기 시작한 시간을 설명하는 문자열 상수로 확장 된다. 문자열 상수는 8개의 문자를 포함하고 `"23:59:01"'과 같다.

__STDC__
This macro expands to the constant 1, to signify that this is ISO Standard C. (Whether that is actually true depends on what C compiler will operate on the output from the preprocessor.) On some hosts, system include files use a different convention, where `__STDC__' is normally 0, but is 1 if the user specifies strict conformance to the C Standard. The preprocessor follows the host convention when processing system include files, but when processing user files it follows the usual GNU C convention. This macro is not defined if the `-traditional' option is used.

        이 매크로는 ISO 표준 C에서 의미하는 상수 1로 확장 된다.( 실제로 C 컴파일러가 전처리기의 출력을 운영하는 것에 의존하는 것이 사실이다) 어떤 호스트들에서는 시스템이 다른 관례로서 `__STDC__'가 0인 파일들을 포함하지만 표준 C에 엄격하게 따라온 유저라면 1로 확장 할 것이다. 전처리기는  처리 시스템이 파일들을 포함할 때 호스트 관례를 따르지만 처리 유저 파일들은 항상 GNU C 관례를 따를 때 호스트의 관례를 따른다. 이 매크로는 `-traditional' 옵션의 사용으로 정의 되지 않는다.

__STDC_VERSION__
This macro expands to the C Standard's version number, a long integer constant of the form `yyyymmL' where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the preprocessor conforms to. Like `__STDC__', whether this version number is accurate for the entire implementation depends on what C compiler will operate on the output from the preprocessor. This macro is not defined if the `-traditional' option is used.

        이 매크로는 C 표준 버전의 숫자로 확장 된다. `yyyymmL`의 형식인long interger 상수이다.  yyyy와 mm은 표준 버전의 년과 달이다. 이것은 C 표준 전처리기에 맞는 버전을 의미한다. `__STDC__’처럼 전처리기로 부터의 출력을 운영할 C 컴파일러에 의존해서 전체 수행이 정확할 지 않을 지 모른다.

__GNUC__
This macro is defined if and only if this is GNU C. This macro is defined only when the entire GNU C compiler is in use; if you invoke the preprocessor directly, `__GNUC__' is undefined. The value identifies the major version number of GNU CC (`1' for GNU CC version 1, which is now obsolete, and `2' for version 2).

        이 매크로는 이것이 GNU C이면 정의 된다. 이 매크로는 전체 GNU C 컴파일러가 사용 될 때만 정의 된다; 만약 당신이 직접적으로 전처리기를 호출 하면, `__GNUC__'는 정의 되지 않는다. 그 값이 GNU CC의 메이저 버전을 확인 한다.(`1' 은 지금은 안 쓰이는 GNU CC 버전 1이고 `2'는 버전 2이다)

__GNUC_MINOR__
The macro contains the minor version number of the compiler. This can be used to work around differences between different releases of the compiler (for example, if GCC 2.6.3 is known to support a feature, you can test for __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6)).

        매크로는 컴파일러의 마이너 버전 숫자를 담고 있다. 이것은 컴파일러의 다른 버전 사이의 차이를 나타낼 때 사용 될 수 있다(예를 들어, 지원되는 형태가 GCC 2.6.3이면  당신은 __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6)를 테스트 할 수 있다.

__GNUC_PATCHLEVEL__
This macro contains the patch level of the compiler. This can be used to work around differences between different patch level releases of the compiler (for example, if GCC 2.6.2 is known to contain a bug, whereas GCC 2.6.3 contains a fix, and you have code which can workaround the problem depending on whether the bug is fixed or not, you can test for __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 6) || (__GNUC__ == 2 && __GNUC_MINOR__ == 6 && __GNUC_PATCHLEVEL__ > 3)).

        이 매크로는 컴파일러의 패치 단계를 담고 있다. 이것은 컴파일러의 다른 패치 단계 배포사이의 차이들을 나타내는데 사용 될 수 있다. ( 예를 들면 만약 GCC 2.6.2가 버그를 담고 있다고 알려지고  GCC 2.6.3가 수정 된 것을 담고 있으면 당신은 버그가 수정 됐는지 안 됐는지에 따라 문제를  나타내는 코드를 가지고 있는 지를 테스트 할 수 있다. __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 6) || (__GNUC__ == 2 && __GNUC_MINOR__ == 6 && __GNUC_PATCHLEVEL__ > 3)).

__GNUG__
The GNU C compiler defines this when the compilation language is C++; use `__GNUG__' to distinguish between GNU C and GNU C++.

        GNU C 컴파일러는 컴파일 언어가 C++일 때 이것을 정의 한다; GNU C와 GNU C++ 를 구별하기 위해 '__GNUG__'을 사용해라

 
__cplusplus
The ISO standard for C++ requires predefining this variable. You can use `__cplusplus' to test whether a header is compiled by a C compiler or a C++ compiler. The compiler currently uses a value of `1', instead of the value `199711L', which would indicate full conformance with the standard.

        C++를 위한  ISO 표준은 이 변수를 미리 정의하는 것을 요구 한다. 당신은 헤더가 C컴파일러로 컴파일 되는지 C++컴파일러로 컴파일 되는지 테스트를 위해 `__cplusplus'를 사용 할 수 있다. 현재 컴파일러는 `199711L'대신에 완전한 일치를 가르키는 `1' 값을 사용한다.

 
__STRICT_ANSI__
GNU C defines this macro if and only if the `-ansi' switch was specified when GNU C was invoked. Its definition is the null string. This macro exists primarily to direct certain GNU header files not to define certain traditional Unix constructs which are incompatible with ISO C.

        GNU C를 호출 했을 때 `-ansi’ 스위치가 지정되어 있어야만 GNU C는 이 매크로를 정의한다. 이 매크로는 우선적으로 ISO C와 함께 할 수 없는 전통적 UNIX 구조가 아닌 어떤GNU 헤더파일들을 지시하는 하기 위해 존재한다.

__BASE_FILE__
This macro expands to the name of the main input file, in the form of a C string constant. This is the source file that was specified on the command line of the preprocessor or C compiler.

        이 매크로는 C 문자열 상수 형태로 주 입력 파일의 이름을 확장한다. 이것은 전처리기와 C 컴파일러의 명령라인에 지정된 소스이다.

 
__INCLUDE_LEVEL__
This macro expands to a decimal integer constant that represents the depth of nesting in include files. The value of this macro is incremented on every `#include' directive and decremented at the end of every included file. It starts out at 0, it's value within the base file specified on the command line.

        이 매크로는 include 파일들에서 nesting의 깊이를 나타내는 10진 정수형 상수로 확장 된다. 이 매크로의 값은 매번 `#include’지시문에서 증가하고 매번 include된 파일의 끝에서 감소 된다. 0에서 시작하고 명령 라인에 지정된 기본 파일 안의 값이다.

__VERSION__
This macro expands to a string constant which describes the version number of GNU C. The string is normally a sequence of decimal numbers separated by periods, such as `"2.6.0"'.

        이 매크로는 GNU C의 버전 숫자를 설명하기 위한 문자열 상수로 확장 된다. 문자열은 보통 마침표로 분리된 10진 숫자들의 나열이다.

 
__OPTIMIZE__
GNU CC defines this macro in optimizing compilations. It causes certain GNU header files to define alternative macro definitions for some system library functions. You should not refer to or test the definition of this macro unless you make very sure that programs will execute with the same effect regardless.

        GNU CC는 최적화 컴파일에 이 매크로를 정의 한다. 몇몇의 시스템 라이브러리 함수들을 위한 대안인 매크로를 정의 하는 것은 어떤 GNU 헤더 파일들의 원인이 된다. 당신이 고려하지 않을 만큼 같은 효과로  프로그램이 실행 될 것을 정말로 확실할 수 있지 않으면 이 매크로의 정의를 테스트하거나  생각하지 말아라

__CHAR_UNSIGNED__
GNU C defines this macro if and only if the data type char is unsigned on the target machine. It exists to cause the standard header file `limits.h' to work correctly. You should not refer to this macro yourself; instead, refer to the standard macros defined in `limits.h'. The preprocessor uses this macro to determine whether or not to sign-extend large character constants written in octal; see section The `#if' Directive.

        GNU C는 데이터 타입 char가 머신에서 부호를 갖지 않으면 이 매크로를 정의 한다. 정확하게 작동하기 위한 표준 헤더 파일 `limits.h' 에서 존재 한다.당신은 당신 스스로 이 매크로를 생각하지 않아야만 한다; 대신, `limits.h'에 정의 된 표준 매크로로 여겨라. 전처리기는 8진수로 쓰여진sign-extend 큰  문자 상수 인지 아닌지 결정하기 위해 이 매크로를 사용한다. The `#if' Directive를 봐라

__REGISTER_PREFIX__
This macro expands to a string (not a string constant) describing the prefix applied to CPU registers in assembler code. You can use it to write assembler code that is usable in multiple environments. For example, in the `m68k-aout' environment it expands to the null string, but in the `m68k-coff' environment it expands to the string `%'.

        이 매크로는 어셈블리 코드에서 CPU 레지스터들로 받아 들여진 접두어를 설명하는 문자열(문자열 상수가 아닌)로 확장 된다. 당신은 다중 환경에서 사용 될 수 있는 어셈블러 코드를 쓰기 위해 그것을 사용할 수 있다. 예를 들어, `m68k-aout'환경에서 널 문자열로 확장 되지만 `m68k-coff'환경에서는 `%'로 확장된다.

__USER_LABEL_PREFIX__
Similar to __REGISTER_PREFIX__, but describes the prefix applied to user generated labels in assembler code. For example, in the `m68k-aout' environment it expands to the string `_', but in the `m68k-coff' environment it expands to the null string. This does not work with the `-mno-underscores' option that the i386 OSF/rose and m88k targets provide nor with the `-mcall*' options of the rs6000 System V Release 4 target.

        __REGISTER_PREFIX__와 비슷하지만 어셈블리 코드에서 유저가 생성한 라벨들로 받아 들여진 접두어를 설명한다. 예를 들어, `m68k-aout'환경에서  그것은 문자열`_'로 확장되지만 `m68k-coff' 환경에서는 널 문자열로 확장된다. 이것은  i386 OSF/rose와 m88k가 목표한  `-mno- unerscores' 옵션으로 작동하지 않고 또한 rs6000 System V Release 4를 목표로 한 옵션도 아니다.

Nonstandard Predefined Macros

The C preprocessor normally has several predefined macros that vary between machines because their purpose is to indicate what type of system and machine is in use. This manual, being for all systems and machines, cannot tell you exactly what their names are; instead, we offer a list of some typical ones. You can use `cpp -dM' to see the values of predefined macros; see section Invoking the C Preprocessor.

C 전처리기는 보통 여러 개의 미리 정의된 머신 사이에서  다양한 매크로를 가진다. 왜냐하면 그들의 목적은 사용되는 시스템과 머신 사이의 타입이 무엇인지를 가리키기 위해서 이다. 이 설명서에서는 모든 시스템들과 머신들에서 존재하는 그들의 이름들이 무엇인지는 정확하게  말해 줄 수 없다; 대신 우리는 몇몇의 전형적인 것들의 리스트를 제공 한다. 당신은  미리 정의된 매크로 값을 보기 위해`cpp -dM'를 사용할 수 있다; Invoking the C Preprocessor 부분을 봐라

Some nonstandard predefined macros describe the operating system in use, with more or less specificity. For example,

몇몇의 비표준으로 미리 정의 된 매크로들은 쓰이고 있는 운영체제의 특성을 많거나 적게 설명한다.

unix
`unix' is normally predefined on all Unix systems.

            `unix'는 보통 모든 유닉스 시스템들에서 미리 정의 되어 있다.

BSD
`BSD' is predefined on recent versions of Berkeley Unix (perhaps only in version 4.3).

        `BSD'는 최근 버클리 유닉스 버전에 미리 정의 되어있다 (아마도 version 4.3에서만)

Other nonstandard predefined macros describe the kind of CPU, with more or less specificity. For example,

다른 비표준으로 미리 정의 된 매크로들은 여러 종류의 CPU의 특성을 많거나 적게 설명한다.

vax
`vax' is predefined on Vax computers.

            `vax'는 Vax 컴퓨터들에 미리 정의 되어 있다

mc68000
`mc68000' is predefined on most computers whose CPU is a Motorola 68000, 68010 or 68020.

        `mc68000'은 CPU가 Motorola 68000, 68010 혹은 68020인 대부분의 컴퓨터들에 미리 정의 되어 있다.

m68k
`m68k' is also predefined on most computers whose CPU is a 68000, 68010 or 68020; however, some makers use `mc68000' and some use `m68k'. Some predefine both names. What happens in GNU C depends on the system you are using it on.

        `m68k’또한 CPU가 68000, 68010 혹은 68020인 대부분의 컴퓨터들에서 미리 정의 되어 있다. 그러나 몇몇 상표들은 `mc68000’을 사용하고 몇몇은 `m68k’를 사용한고 몇몇은 둘다 사용한다.GNU C에서 발생하는 것은 당신이 사용 중인 시스템에 의존한다.

M68020
`M68020' has been observed to be predefined on some systems that use 68020 CPUs -- in addition to `mc68000' and `m68k', which are less specific.

        `M68020'은 68020 CPU들을 사용하는 몇몇 시스템들에 미리 정의 되어 있는 것으로 관찰 되어 왔다.-덧붙여 `mc68000'과 `m68k'는 덜 구체적이다.

_AM29K
_AM29000
Both `_AM29K' and `_AM29000' are predefined for the AMD 29000 CPU family.

        `_AM29K' 그리고 `_AM29000' 둘다 AMD 29000 CPU 시리즈를 위해 미리 정의 되어 있다.

ns32000
`ns32000' is predefined on computers which use the National Semiconductor 32000 series CPU.

        `ns32000'은 the National Semiconductor 32000 series CPU를 사용하는 컴퓨터들에 미리 정의 되어 있다.

Yet other nonstandard predefined macros describe the manufacturer of the system. For example,

아직 다른 비표준으로 미리 정의된 매크로들은 시스템의 회사명으로 설명한다. 예를 들면,

sun
`sun' is predefined on all models of Sun computers.

        Sun 컴퓨터들의 모든 모델들을 `sun'으로 미리 정의 된다.

pyr
`pyr' is predefined on all models of Pyramid computers.

        `pyr'는 Pyramid 컴퓨터들의 모든 모델에서 미리 정의 된다

sequent
`sequent' is predefined on all models of Sequent computers.

        `sequent'는 Sequent 컴퓨터들의 모든 모델에서 미리 정의 된다.

These predefined symbols are not only nonstandard, they are contrary to the ISO standard because their names do not start with underscores. Therefore, the option `-ansi' inhibits the definition of these symbols.

미리 정의 된 심벌들은 비표준일 뿐만 아니라 ISO표준에 적합하지 않다. 왜냐하면 그들의 이름은 언더스코어로 시작하지 않는다. 그러므로, `-ansi'옵션은 이 심벌들의 정의를 못하게 한다.

This tends to make `-ansi' useless, since many programs depend on the customary nonstandard predefined symbols. Even system header files check them and will generate incorrect declarations if they do not find the names that are expected. You might think that the header files supplied for the Uglix computer would not need to test what machine they are running on, because they can simply assume it is the Uglix; but often they do, and they do so using the customary names. As a result, very few C programs will compile with `-ansi'. We intend to avoid such problems on the GNU system.

많은 프로그램들이 관례적인 비표준으로 정의된 심벌들에 의존하기 때문에 `-ansi' 옵션을 쓸모 없게 하기 쉽다. 시스템 파일들이 그것들을 체크하지만 예상한 이름을 찾지 못하면 정확하지 않은 선언이 발생 할 수 있다. 당신은 Uglix 컴퓨터에 제공 되는 헤더 파일들은 머신에서 작동하는지를 테스트 할 필요가 없다고 생각할 모른다. 왜냐하면 헤더파일들은 쉽게 그것이 Uglix라고 생각 할 수 있기 때문이다; 그러나 자주 그렇게 하지만 그것들은 또한 자주 관습적인 이름들로 사용 한다. 그 결과 매우 적은 C 프로그램들이 `-ansi'로 컴파일 될 것이다. 우리는 GNU 시스템에서 그런 문제를 피하려고 한다.

What, then, should you do in an ISO C program to test the type of machine it will run on?

실행될 머신 타입을 테스트하기 위해 ISO C 프로그램에 당신은 무엇을 해야만 하는가?

GNU C offers a parallel series of symbols for this purpose, whose names are made from the customary ones by adding `__' at the beginning and end. Thus, the symbol __vax__ would be available on a Vax, and so on.

GNU C는 이 목적을 위해 심벌들의 병렬 시리즈들을 제공한다.병렬 시리즈들은 시작과 끝에 `__'을 더함으로써 관례적으로 만든다.게다가 심볼 __vax__는 Vax나 그 밖에 것들로 사용 된다.

The set of nonstandard predefined names in the GNU C preprocessor is controlled (when cpp is itself compiled) by the macro `CPP_PREDEFINES', which should be a string containing `-D' options, separated by spaces. For example, on the Sun 3, we use the following definition:

비표준으로 미리 정의 된 GNU전처리기에 이름들의 집합은 `CPP_PREDEFINES' 매크로에 의해 통제(cpp가 스스로 컴파일 될 때) 된다. 그리고 `-D'옵션을 포함한 문자열이어야 하고 공간으로 분리되어 있어야 한다. 예를 들면  Sun 3은 다음의 정의를 따른다.

#define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"

This macro is usually specified in `tm.h'.

이 매크로는 항상 `tm.h'에 지정된다.

Stringification

Stringification means turning a sequence of preprocessing tokens into a string literal. For example, stringifying `foo (z)' results in `"foo (z)"'.

Stringification은 전처리 되는 토큰들의 열이 문자열 그대로 전환되는 것을 의미한다. 예를 들면, stringigying `foo(z)'의 결과는  `"foo (z)"' 이다.

In the C preprocessor, stringification is possible when macro arguments are substituted during macro expansion. When a parameter appears preceded by a `#' token in the replacement list of a function-like macro, it indicates that both tokens should be replaced with the stringification of the corresponding argument during expansion. The same argument may be substituted in other places in the definition without stringification if the argument name appears in those places with no preceding `#'.

C 전처리기에서stringification은 매크로가 확장되는 동안에 매크로 인자들이 대체될 때 가능하다. 파라미터가 function-like 매크로의 대체 리스트에서 `#' 토큰 보다 먼저 나타날 때, 토큰들이 매크로가 확장하는 동안 일치하는 인자의 stringifiation으로 바뀌어야 하는 것을 가르킨다. 인자 이름이 `#'이 선행 되지 않고 그런 곳에 나타난다면 같은 인자는 다른 곳에서  stringification 없는 정의로 대체 될지 모른다.

Here is an example of a macro definition that uses stringification:

stringification을 이용한 매크로 정의의 예가 여기 있다.

#define WARN_IF(EXP) \
do { if (EXP) \
        fprintf (stderr, "Warning: " #EXP "\n"); } \
while (0)

Here the argument for `EXP' is substituted once, as-is, into the `if' statement, and once, stringified, into the argument to `fprintf'. The `do' and `while (0)' are a kludge to make it possible to write `WARN_IF (arg);', which the resemblance of `WARN_IF' to a function would make C programmers want to do; see section Swallowing the Semicolon.

여기서 인자 ' EXP '는 한 번 `if' 진술로 치환되고  한번 `fprintf'에 인자로 stringified 된다. `do'와 `while(0)'는 `WARN_IF(arg);'를 쓰는 것을 가능하게 만드는 다소 귀찮은 문제에 대한 좋은 해결책이다.  함수와 유사한 `WARN_IF' 은 C 프로그래머가 하고 싶은 것을 만든다.; Swallowing the Semicolon.를 봐라

The stringification feature is limited to transforming the tokens of a macro argument into a string constant: there is no way to combine the argument with surrounding text and stringify it all together. The example above shows how an equivalent result can be obtained in ISO Standard C, using the fact that adjacent string constants are concatenated by the C compiler to form a single string constant. The preprocessor stringifies the actual value of `EXP' into a separate string constant, resulting in text like

stringification 특징은 매크로 인자 토큰들을 문자열 상수로 변환하는 것이 제한 된 것이다.: 텍스트로 둘러 쌓인 인자를 합치는 것과 그것을 모두 함께 문자열로 만드는 것은 불가능하다. 위의 예는  인접한 문자열 상수들이 C 컴파일러에 의해 단일 문자열 상수 형태로 연결되는 것을 이용해서  ISO 표준 C에서 같은 결과가 어떻게 얻어 질 수 있는지를 보여준다. 전처리기는 `EXP'의 실제 값을 분리된 문자열 상수로 문자열화한다.

do { if (x == 0) \
        fprintf (stderr, "Warning: " "x == 0" "\n"); } \
while (0)

but the compiler then sees three consecutive string constants and concatenates them into one, producing effectively

그러나 컴파일러는 세 개의 연속적인 문자열 상수들을 보고 효과적으로 그것들을 하나로 연결한다.

do { if (x == 0) \
        fprintf (stderr, "Warning: x == 0\n"); } \
while (0)

Stringification in C involves more than putting double-quote characters around the fragment. The preprocessor backslash-escapes the surrounding quotes of string literals, and all backslashes within string and character constants, in order to get a valid C string constant with the proper contents. Thus, stringifying `p = "foo\n";' results in `"p = \"foo\\n\";"'. However, backslashes that are not inside string or character constants are not duplicated: `\n' by itself stringifies to `"\n"'.

C에서 Stringification는 파편들 주의에 double-quote 문자들을 놓는 것을 보다 더 포함한다. backslash-escapes로 둘러 쌓인 전처리기는 문자열 그대로 인용되고 문자열과 문자 상수 내에서의 백슬래쉬들도 인용된다. 이것은 적절한 내용에 정당한 C문자열 상수를 얻기 위해서 이다. 그러나, 문자열 또는 문자들 안에 없는 백슬래쉬들은 중복되지 않는다: `\n'은 스스로 `"\n"'로 stringifies 한다.

Whitespace (including comments) in the text being stringified is handled according to precise rules. All leading and trailing whitespace is ignored. Any sequence of whitespace in the middle of the text is converted to a single space in the stringified result.

문자열화 된 텍스트에 공백(주석을 포함한)은 정확한 규칙에 따라 다루어진다. 모든 앞 뒤 공백은 무시된다. 텍스트 중간에 어떤 공백의 열도 문자열화 된 결과로 하나의 공간으로 바뀐다.  

Concatenation

Concatenation means joining two strings into one. In the context of macro expansion, concatenation refers to joining two preprocessing tokens to form one. In particular, a token of a macro argument can be concatenated with another argument's token or with fixed text to produce a longer name. The longer name might be the name of a function, variable, type, or a C keyword; it might even be the name of another macro, in which case it will be expanded.

연결은 두개의 문자열을 하나로 결합시키는 것을 의미한다. 매크로 확장 내용에서 연결은 하나의 형태로 두개의 전처리 토큰들을 결합 시키는 것으로 여긴다.  특히 매크로 인자 토큰은 다른 인자의 토큰이나 더 긴 이름을 만들기 위한 고정된 텍스트로 연결 될 수 있다. 더 긴 이름은 함수, 변수, 타입 또는 C keyword가 될지 모른다; 그것은 확장되어질 경우 다른 매크로의 이름이 될지도 모른다.

When you define a function-like or object-like macro, you request concatenation with the special operator `##' in the macro's replacement list. When the macro is called, any arguments are substituted without performing macro expansion, every `##' operator is deleted, and the two tokens on either side of it are concatenated to form a single token.

당신이 function-like나 object-like 매크로를 정의 할 때 매크로의 교체 목록에서 특별한`##' 연산자로 연결을 요청한다. 매크로가 불러지면 어떤 인자들도 매크로 확장의 수행 없이 대체 된다. 모든 `##' 연산자는 제거되고 그것의 양쪽에 토큰들은 하나의 토큰 형태로 연결된다.

Consider a C program that interprets named commands. There probably needs to be a table of commands, perhaps an array of structures declared as follows:

이름 지어진 명령들을 해석하는  C 프로그램을 생각해봐라. 아마도 명령 테이블이 필요할 것이다. 아마도 뒤따르는 선언된 구조체의 배열도 일 것이다.

struct command
{
  char *name;
  void (*function) ();
};

struct command commands[] =
{
  { "quit", quit_command},
  { "help", help_command},
  ...
};

It would be cleaner not to have to give each command name twice, once in the string constant and once in the function name. A macro which takes the name of a command as an argument can make this unnecessary. The string constant can be created with stringification, and the function name by concatenating the argument with `_command'. Here is how it is done:

각 명령 이름들을 두 번 주는 것은 깔끔하지 않다. 한번은 문자열 상수와 한번은 함수 이름이다. 인자로써 명령의 이름을 받아들이는 매크로는 이것을 불필요하게 만들 수 있다. 문자열 상수는 stringification 으로 만들어질 수 있고 `_command' 와 함께 인자를 연결해서 함수 이름으로 만들 수 있다. 어떻게 하는지 봐라

#define COMMAND(NAME)  { #NAME, NAME ## _command }

struct command commands[] =
{
  COMMAND (quit),
  COMMAND (help),
  ...
};

The usual case of concatenation is concatenating two names (or a name and a number) into a longer name. This isn't the only valid case. It is also possible to concatenate two numbers (or a number and a name, such as `1.5' and `e3') into a number. Also, multi-character operators such as `+=' can be formed by concatenation. However, two tokens that don't together form a valid token cannot be concatenated. For example, concatenation of `x' on one side and `+' on the other is not meaningful because those two tokens do not form a valid preprocessing token when concatenated. UNDEFINED

연결의 경우 항상 두 이름들을( 또는 하나의 이름과 하나의 숫자) 더 긴 이름으로 연결 한다. 이것만이 항상 정당한 경우는 아니다. 또한 두개의 숫자들(또는 하나의 숫자와 하나의 이름, `1.5' 와 'e3'와 같은)을 하나의 숫자로 연결 할 수 있다. 또한 `+='과 같은 다중-문자 연산자는 연결에 의해 형식화 될 수 있다. 그러나 올바른 토큰으로 형식화 되지 않는 두 개의 토큰들은 연결 될 수 없다. 예를 들면 한 쪽은 `x'고 다른 쪽은 `+'인 연결은 두개의 토큰들이 연결 될 때 정당한 전처리 토큰 형태가 아니기  때문에 의미가 없다. 정의 안 된다.  

Keep in mind that the C preprocessor converts comments to whitespace before macros are even considered. Therefore, you cannot create a comment by concatenating `/' and `*': the `/*' sequence that starts a comment is not a token, but rather the beginning of a comment. You can freely use comments next to `##' in a macro definition, or in arguments that will be concatenated, because the comments will be converted to spaces at first sight, and concatenation operates on tokens and so ignores whitespace.

매크로로 생각하기 전에 주석을 공백으로 전환하는 것을 명심해라. 그러므로 당신은 `/'과 '*' 연결에 의해 주석을 만들 수 없다.: 주석을 시작하는 `/*' 열은  토큰이 아니라 주석의 시작이다. 당신은 자유롭게 매크로 정의나 또는 연결 되어질 인자에서  `##' 다음에 주석을 이용할 수 있다. 왜냐하면 주석들은 첫 눈에 공간으로 전환 될 것이고 토큰에 연결이 수행되고 그래서 공백은 무시 되기 때문이다.

Undefining Macros

To undefine a macro means to cancel its definition. This is done with the `#undef' directive. `#undef' is followed by the macro name to be undefined.

매크로로 정의를 undefine한다는 것은 그것의 정의를 취소하는 것을 의미한다. `#undef' 지시문으로 된다. `#undef' 뒤에는 정의가 취소될  매크로 이름이 따라 온다.

Like definition, undefinition occurs at a specific point in the source file, and it applies starting from that point. The name ceases to be a macro name, and from that point on it is treated by the preprocessor as if it had never been a macro name.

정의 처럼, 정의의 취소는 소스 파일에 특정 지점에서 발생하고 그 지점에서 적용된다.  그 지점에서 매크로 이름은 취소 되고 결코 매크로 이름이지 않았던 것처럼 전처리기에 의해 다루어 진다.

For example,

#define FOO 4
x = FOO;
#undef FOO
x = FOO;

expands into

x = 4;

x = FOO;

In this example, `FOO' had better be a variable or function as well as (temporarily) a macro, in order for the result of the expansion to be valid C code.

이 예에서 `F00' 는 확장의 결과가 올바른 C 코드가 되기 위해서 (임시적으로) 매크로와 마찬가지로 변수나 함수가 되는 것이 더 낫다.

The same form of `#undef' directive will cancel definitions with arguments or definitions that don't expect arguments. The `#undef' directive has no effect when used on a name not currently defined as a macro.

`#undef' 지시문과 같은 형식은 인자들이나 인자를 필요로 하지 않는 정의들에 정의를 취소 할 것이다. `#undef' 지시문은 매크로로써 현재 정의 되지 않은 이름을 사용할 때 전혀 효과가 없다.  

Redefining Macros

Redefining a macro means defining (with `#define') a name that is already defined as a macro.

Redefining은 매크로로써 이미 정의된 이름을 (`#defind'으로) 정의 하는 것을 의미한다.

A redefinition is trivial if the new definition is transparently identical to the old one. You probably wouldn't deliberately write a trivial redefinition, but they can happen automatically when a header file is included more than once (see section Header Files), so they are accepted silently and without effect.

재정의는 새로운 정의가 명백하게 전에 정의와 같다면 사소한 것이다. 아마도 당신은 신중하게 하찮은 재정의를 쓰는 것이 아니고 그것들은 헤더 파일이 한번 더 소스에 포함될 때 자동적으로 발생한다. 그래서 그것들은 소리 없이 받아 들여지고 효과도 없다.

Nontrivial redefinition is considered likely to be an error, so it provokes a warning message from the preprocessor. However, sometimes it is useful to change the definition of a macro in mid-compilation. You can inhibit the warning by undefining the macro with `#undef' before the second definition.

사소하지 않은 재정의는 에러 같이 생각 될지 모른다. 그래서 전처리기로부터 경고를 야기 시킨다. 그러나 가끔 중간 컴파일에서 매크로 정의를 바꿀 때 유용하다. 당신은 두 번째 정의 전에 `#undef'로 정의를 취소해서 경고를 금지 할 수 있다.

In order for a redefinition to be trivial, the parameter names must match and be in the same order, and the new replacement list must exactly match the one already in effect, with two possible exceptions:

사소한 재정의를 위해서, 파라미터 이름들은 일치해야 하고 같은 순서가 되어야만 한다. 그리고 새로운 교체 목록은 정확하게 효과가 일치해야만 한다. 두 가지 가능한 예외가 있다.

Recall that a comment counts as whitespace.

공백으로써 주석을 여기는 것을 다시 상기시켜라.

As a particular case of the above, you may not redefine an object-like macro as a function-like macro, and vice-versa.

위의 특별한 예로써 당신은function-like 매크로 같이 object-like 매크로를 재정의 하지 않을 것이다. 반대의 경우도 마찬가지다.  

Poisoning Macros

Sometimes, there is an identifier that you want to remove completely from your program, and make sure that it never creeps back in. To enforce this, the `#pragma GCC poison' directive can be used. `#pragma GCC poison' is followed by a list of identifiers to poison, and takes effect for the rest of the source. You cannot `#undef' a poisoned identifier or test to see if it's defined with `#ifdef'.

때때로 당신이 원하는 것을 당신의 프로그램에서 완벽하게 제거하는 것을 원하는 식별자가 있다. 그리고 결코 그것은 다시 슬쩍( ^^;) 들어오지 않는 것을 확신 할 수 있기를 원할 것이다. 이것을 강제적으로 제한 하기 위해서 `#pragma GCC poison' 지시문이 사용 될 수 있다. `#prgma GCC poison' 뒤에는 poison에 식별자들의 목록이 나온다. 그리고 소스의 나머지를 위한 노력이 온다( ^^~). 당신은 못쓰게 된 식별자들을 `#undef' 할 수 없고, 또한 `#ifdef'로 정의 하면 보이는지 테스트 할 수 없다.

For example,

예를 들면

#pragma GCC poison printf sprintf fprintf
sprintf(some_string, "hello");

will produce an error.

에러가 발생 한다.

Pitfalls and Subtleties of Macros

In this section we describe some special rules that apply to macros and macro expansion, and point out certain cases in which the rules have counterintuitive consequences that you must watch out for.

이 섹션에서 우리는 매크로를 적용과 확장에 대한  몇 개의 특별한 규칙들을 설명한다. 그리고 당신이 봐야만 하는 counterintuitive consequences를 갖는 규칙에 확실한 경우를 지적한다.

Improperly Nested Constructs

Recall that when a macro is called with arguments, the arguments are substituted into the macro body and the result is checked, together with the rest of the input file, for more macro calls.

인자들과 함께 매크로가 호출 될 때 인자들은 매크로 몸체로 대체 되고 결과는 입력 파일들의 나머지와 함께 더 많은 매크로 호출을 위해 체크된다.

It is possible to piece together a macro call coming partially from the macro body and partially from the arguments. For example,

매크로 몸체와 인자들로부터 부분적으로 오는 매크로 호출을 함께 단편화 하는 것이 가능하다. 예를 들면,

#define double(x) (2*(x))
#define call_with_1(x) x(1)

would expand `call_with_1 (double)' into `(2*(1))'.

Macro definitions do not have to have balanced parentheses. By writing an unbalanced open parenthesis in a macro body, it is possible to create a macro call that begins inside the macro body but ends outside of it. For example,

매크로 정의들은 균형 맞은 괄호들을 갖지 않아야만 한다. 균형이 맞지 않는 매크로 몸체에 열기 괄호는 매크로 몸체 안에서 (끝에 바깥쪽은 제외하고) 시작하는 매크로를 만들 수 있다. 예를 들면,

#define strange(file) fprintf (file, "%s %d",
...
strange(stderr) p, 35)

This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!

이 끔찍한 예는 `fprintf (stderr, "%s %d", p, 35)'로 확장 된다. ㅡㅡ;

Unintended Grouping of Arithmetic

You may have noticed that in most of the macro definition examples shown above, each occurrence of a macro argument name had parentheses around it. In addition, another pair of parentheses usually surround the entire macro definition. Here is why it is best to write macros that way.

당신은 대부분의 위에서 보여준 매크로 정의 예에서 매크로 인자들이 발생하면 그것의 주위에 괄호가 있던 것을 알아 챘는지 모르겠다. 덧붙이자면 다른 괄호의 쌍들이 항상 전체 매크로 정의를 감사고 있다. 여기서 왜 그 방법이 매크로들을 쓰는 최고의 방법인지를 쓰겠다.

Suppose you define a macro as follows,

다음과 같은 정의를 가정해 보자.

#define ceil_div(x, y) (x + y - 1) / y

whose purpose is to divide, rounding up. (One use for this operation is to compute how many `int' objects are needed to hold a certain number of `char' objects.) Then suppose it is used as follows:

나누고 올림하기 위한 것이다.( 한 사용법은 얼마나 많은 `int' 객체가 `char' 객체들의 확실한 숫자를 고정하기 위해 필요한지를 계산하기 위한 것이다. 그 다음에 그것이 다음과 같이 쓰인다고 가정하자.

a = ceil_div (b & c, sizeof (int));

This expands into

이것은 다음으로 확장 된다.

a = (b & c + sizeof (int) - 1) / sizeof (int);

which does not do what is intended. The operator-precedence rules of C make it equivalent to this:

의도 된 것은 하지 않는다. operator-precedence C의 규칙들은 이것을 동등하게 만든다.

a = (b & (c + sizeof (int) - 1)) / sizeof (int);

What we want is this:

이것이 우리가 원하는 것이다.

a = ((b & c) + sizeof (int) - 1)) / sizeof (int);

Defining the macro as

#define ceil_div(x, y) ((x) + (y) - 1) / (y)

provides the desired result.

Unintended grouping can result in another way. Consider `sizeof ceil_div(1, 2)'. That has the appearance of a C expression that would compute the size of the type of `ceil_div (1, 2)', but in fact it means something very different. Here is what it expands to:

의도 하지 않은 그룹화는 다른 결과를 낳을 수 있다. `sizeof ceil_div(1, 2)'를 고려해봐라. 그것은 `ceil_div (1, 2)' 타입의 사이즈를 계산하는 C 표현의 외형을 갖는다. 하지만 사실 그것은 매우 다른 의미를 갖느다. 여기 확장된 것이 있다

sizeof ((1) + (2) - 1) / (2)

This would take the size of an integer and divide it by two. The precedence rules have put the division outside the `sizeof' when it was intended to be inside.

이것은 정수 크기를 받고 2로 그것을 나눈다. 선행된 규칙들은 나누는 수를 `sizeof'  바깥에 놨다. 그것이 안에 놓여지게 의도되어야 할 때 말이다.

Parentheses around the entire macro definition can prevent such problems. Here, then, is the recommended way to define `ceil_div':

전체 매크로 정의에 괄호는 그런 문제들을 막을 수 있다. `ceil_div'를 정의 하는 방법으로 추천되는 방법이 있다.:

#define ceil_div(x, y) (((x) + (y) - 1) / (y))

Swallowing the Semicolon

Often it is desirable to define a macro that expands into a compound statement. Consider, for example, the following macro, that advances a pointer (the argument `p' says where to find it) across whitespace characters:

복잡한 문장으로 확장되는 매크로를 정의 하는 것은 매력적이다. 예를 들어, 공백 문자들로 가로지르는 포인터를  개선 시키는 것을 생각해 봐라.

#define SKIP_SPACES(p, limit)  \
{ register char *lim = (limit); \
  while (p != lim) {            \
    if (*p++ != ' ') {          \
      p--; break; }}}

Here backslash-newline is used to split the macro definition, which must be a single logical line, so that it resembles the way such C code would be laid out if not part of a macro definition.

backslash-newline은 한 논리 라인이 되야만 하는 매크로 정의를 나누는데 사용된다. 그래서 매크로 정의 부분이 아니라면  C 코드에서 쓰는 방법을 닮았다

A call to this macro might be `SKIP_SPACES (p, lim)'. Strictly speaking, the call expands to a compound statement, which is a complete statement with no need for a semicolon to end it. However, since it looks like a function call, it minimizes confusion if you can use it like a function call, writing a semicolon afterward, as in `SKIP_SPACES (p, lim);'

이 매크로 호출은  `SKIP_SPACES (p, lim)'가 될 것이다. 엄밀하게 말해서 복잡한 문장으로 확장된 호출에서 그것의 완전한 문장은 끝에 세미콜론이 필요하지 않다. 그러나 함수 호출 처럼 보이기 때문에 당신이 뒤쪽에 `SKIP_SPACES (p, lim);'처럼 세미콜론을 쓰면 함수 같이 사용해도 혼란을 최소화 할 수 있다.

This can cause trouble before `else' statements, because the semicolon is actually a null statement. Suppose you write

이것은 `else' 문장 전에 문제를 야기 시킬 수 있다. 왜냐하면 세미콜론은 실제로 null 문장이다.

if (*p != 0)
  SKIP_SPACES (p, lim);
else ...

The presence of two statements -- the compound statement and a null statement -- in between the `if' condition and the `else' makes invalid C code.

`if' 조건과 `else'  사이에 두 문장- 복잡한 문장과 null 문장-- 의 존재는 올바르지 않은 C 코드를 만든다.

The definition of the macro `SKIP_SPACES' can be altered to solve this problem, using a `do ... while' statement. Here is how:

매크로 `SKIP_SPACES'는 이 문제를 해결하기 위해 `do ... while'문장을 사용해서 바뀔 수 있다.

#define SKIP_SPACES(p, limit)     \
do { register char *lim = (limit); \
     while (p != lim) {            \
       if (*p++ != ' ') {          \
         p--; break; }}}           \
while (0)

Now `SKIP_SPACES (p, lim);' expands into

do {...} while (0);

which is one statement.

Duplication of Side Effects

Many C programs define a macro `min', for "minimum", like this:

많은 C 프로그램들은 "최소"에 대해 `min'를 정의 한다. 이것과 같다.

#define min(X, Y)  ((X) < (Y) ? (X) : (Y))

When you use this macro with an argument containing a side effect, as shown here,

당신이 부가적 효과를 포함하는 인자를 이 매크로에 사용할 때는 아래와 같다.

next = min (x + y, foo (z));

it expands as follows:

다음 처럼 확장 된다

next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));

where `x + y' has been substituted for `X' and `foo (z)' for `Y'.

`x + y'는 `X'로 대체 되고 와 `foo(z)'는 Y로 대체 된다.

The function `foo' is used only once in the statement as it appears in the program, but the expression `foo (z)' has been substituted twice into the macro expansion. As a result, `foo' might be called two times when the statement is executed. If it has side effects or if it takes a long time to compute, the results might not be what you intended. We say that `min' is an unsafe macro.

`foo' 함수는 프로그램에 나타나는 거처럼 문장에 오직 한번 사용된다. 그러나 `foo(z)' 표현은 매크로 확장으로 두 번 대체 되어진다. 결과로써, `foo'는 문장이 실행될 때 두 번 불려질지 모른다. 부가적 효과를 갖거나 또는 계산하는데 오랜 시간이 소모 된다면 결과는 당신이 의도한 것이 아닐지도 모른다. 우리는 `min'은 안전하지 않은 매크로라고 말한다.

The best solution to this problem is to define `min' in a way that computes the value of `foo (z)' only once. The C language offers no standard way to do this, but it can be done with GNU C extensions as follows:

이 문제를 해결하는 최고의 방법은 `min'을 오직 한번 `foo (z)' 값으로 계산하는 것이다. C 언어는 이것을 하는 표준 방법을 제공하지 않지만 GNU C 확장으로 다음처럼 할 수 있다.

#define min(X, Y)                     \
({ typeof (X) __x = (X), __y = (Y);   \
   (__x < __y) ? __x : __y; })

If you do not wish to use GNU C extensions, the only solution is to be careful when using the macro `min'. For example, you can calculate the value of `foo (z)', save it in a variable, and use that variable in `min':

만약에 당신이 GNU C 확장들을 사용하는 것을 원하지 않는 다면 매크로 `min'을 조심스럽게 사용하는 방법 밖에 없다. 예를 들면 당신은 `foo(z)를 변수에 저장하고 `min'에 그 변수를 사용해서  `foo(z)' 값을 계산 할 수 있다.

#define min(X, Y)  ((X) < (Y) ? (X) : (Y))
...
{
  int tem = foo (z);
  next = min (x + y, tem);
}

(where we assume that `foo' returns type `int').

Self-Referential Macros

A self-referential macro is one whose name appears in its definition. A special feature of ISO Standard C is that the self-reference is not considered a macro call. It is passed into the preprocessor output unchanged.

자기 참조 매크로는 그것의 정의에 이름이 나타나는 것이다. ISO 표준 C의 특별한 특징은 자기 참조는 매크로 호출로 고려되지 않는 것이다. 그것은 바뀌지 않은 전처리 출력으로 통과된다.

Let's consider an example:

예를 생각해 보자

#define foo (4 + foo)

where `foo' is also a variable in your program.

`foo'는 또한 당신 프로그램의 변수이다.

Following the ordinary rules, each reference to `foo' will expand into `(4 + foo)'; then this will be rescanned and will expand into `(4 + (4 + foo))'; and so on until it causes a fatal error (memory full) in the preprocessor.

보통의 규칙들에 따라 각각의 `foo'에서 참조는 `(4 + foo)'로 확장될 것이다; 그 다음에 이것은 다시 검색되고 `(4 + (4 + foo))' 로 확장될 것이다; 그리고 그것이 메모리가 다 차는 치명적인 전처리기 에러를 야기 시킬 때 까지 계속 될 것이다.

However, the special rule about self-reference cuts this process short after one step, at `(4 + foo)'. Therefore, this macro definition has the possibly useful effect of causing the program to add 4 to the value of `foo' wherever `foo' is referred to.

그러나. 자기 참조에 대한 특별한 규칙은 한번에 스텝 뒤에서 이 프로세스는 짧게 끊는다. 그러므로 이 매크로 정의는 `foo`가 참조되는 어느 곳에서든지 `foo'의 값에 4를 더하는 프로그램 효과를 얻기에 유용할 수 있다.

In most cases, it is a bad idea to take advantage of this feature. A person reading the program who sees that `foo' is a variable will not expect that it is a macro as well. The reader will come across the identifier `foo' in the program and think its value should be that of the variable `foo', whereas in fact the value is four greater.

대부분의 경우, 이 특징의 이점을 받아들이는 것이 좋지 않은 생각이다. `foo` 변수를 당신 프로그램에서 읽는 사람은 이 매크로에 대해 전혀 예상 하지 못 할 것이다. 읽는 사람은 프로그램에서 `foo' 식별자를 건너 띄고 그것의 값은 `foo' 변수가 되야 한다고 생각할 것이다. 반면에 사실 값은 4가 더 큰 것인데..

The special rule for self-reference applies also to indirect self-reference. This is the case where a macro x expands to use a macro `y', and the expansion of `y' refers to the macro `x'. The resulting reference to `x' comes indirectly from the expansion of `x', so it is a self-reference and is not further expanded. Thus, after

자기 참조에 대한 특별한 규칙은 또한 자기참조를 간접적으로 적용한다. 이것은 매크로 x가 매크로 `y'를 사용해서 확장되는 경우이다. 그리고 `y'의 확장은 매크로 `x'를 참조 된다. `x' 참조의 결과는 간접적으로 `x'의 확장으로부터 온다. 그래서 그것은 자기 참조이고 더 확장되지 않는다.

#define x (4 + y)
#define y (2 * x)

`x' would expand into `(4 + (2 * x))'. Clear?

Suppose `y' is used elsewhere, not from the definition of `x'. Then the use of `x' in the expansion of `y' is not a self-reference because `x' is not "in progress". So it does expand. However, the expansion of `x' contains a reference to `y', and that is an indirect self-reference now because `y' is "in progress". The result is that `y' expands to `(2 * (4 + y))'.

`y'가 쓰이는 'x'의 정의로부터 정의 되지 않는 다른 곳을 가정하자. 그 다음에 `x'를 `y'의 확장에 사용하는 것은 자기 참조가 아니다. 왜냐하면 `x'는 "in progress"가 아니기 때문이다. 그래서 그것은 확장된다. 그러나 `x'확장은 `y' 참조를 포함한다. 그리고 그것은 `y'가 "in progress" 이기 때문에 간접적인 자기 참조이다. 결과는 'y'는 `(2 * (4 + y))'로 확장 된다.

This behavior is specified by the ISO C standard, so you may need to understand it.

이 행동들은 ISO C표준에 의해 구체화 되었다. 그래서 당신은 그것을 이해하는 것이 필요할 것이다.

Separate Expansion of Macro Arguments

We have explained that the expansion of a macro, including the substituted arguments, is re-scanned for macro calls to be expanded.

우리는 대체되는 인자들을 포함해서 매크로 확장을 매크로 호출이 확장되는 것으로 다시 검색하는 것을 설명해 왔다

What really happens is more subtle: first each argument is scanned separately for macro calls. Then the resulting tokens are substituted into the macro body to produce the macro expansion, and the macro expansion is scanned again for macros to expand.

정말로 일어난 것은 더 구별하기 어렵다: 처음 각각의 인자는 매크로 호출들을 위해 분리 되서 검색된다. 그 다음에 결과 토큰은 매크로 확장을 만드는 매크로 몸체로 대체된다. 그리고 매크로 확장은 다시 매크로가 확장되는 것을 검색한다.

The result is that the arguments are scanned twice to expand macro calls in them.

결과는 인자들이 확장되는 매크로 호출에서 두 번 스캔된다.

Most of the time, this has no effect. If the argument contained any macro calls, they are expanded during the first scan. The result therefore contains no macro calls, so the second scan does not change it. If the argument were substituted as given, with no prescan, the single remaining scan would find the same macro calls and produce the same results.

대체로 이것은 효과가 없다. 만약 어떤 매크로 호출에 포함된 인자들이라면 그것들은 처음 검색동안 확장 될 것이다. 그러므로 결과는 아무 매크로 호출도 포함하지 않는다. 그래서 두 번째 검색에서는 그것이 바뀌지 않는다. 만약 선행 검색 없이 인자가 주어진 것처럼 대체 되면, 하나 남은 검색은 같은 매크로 호출들을 찾을 것이고 같은 결과를 만들 것이다.

You might expect the double scan to change the results when a self-referential macro is used in an argument of another macro (see section Self-Referential Macros): the self-referential macro would be expanded once in the first scan, and a second time in the second scan. However, this is not what happens. The self-references that do not expand in the first scan are marked so that they will not expand in the second scan either.

자기 참조 매크로가 다른 매크로의 인자를 사용할 때 당신은 바뀐 결과에 두 번 검색을 예상할 지 모른다: 자기참조 매크로는 첫 검색에서 한번 확장된다. 그리고 다음 검색에서 두 번째로 확장될 것이다. 그러나 이것은 일어나지 않는다. 첫 검색에서 확장하지 않는 자기 참조는 두 번째 검색에서도 또한 확장하지 않기 위해 표시 될 것이다..

The prescan is not done when an argument is stringified or concatenated. Thus,

선행 검색은 인자가 문자열화 또는 연결되지 않을 때 끝나지 않는다. 게다가

#define str(s) #s
#define foo 4
str (foo)

expands to `"foo"'. Once more, prescan has been prevented from having any noticeable effect.

`"foo"'로 확장 된다. 일단 선행검색은 어떤 주의할 만한 영향을 갖는 것을 방지 한다..

More precisely, stringification and concatenation use the argument tokens as given without initially scanning for macros. The same argument would be used in expanded form if it is substituted elsewhere without stringification or concatenation.

좀 더 정확하게, stringfication 그리고 연결은 인자 토큰들은 주어진 것처럼 매크로를 위한 초기화 검색없이 사용한다. 같은 인자는 만약 그것이 stringification 또는 연결 없이 다른 곳에서 대체 된다면 확장된 형식에 사용 될 것이다.

#define str(s) #s lose(s)
#define foo 4
str (foo)

expands to `"foo" lose(4)'.

You might now ask, "Why mention the prescan, if it makes no difference? And why not skip it and make the preprocessor faster?" The answer is that the prescan does make a difference in three special cases:

당신이 지금 물어 볼지도 모르겠다. "왜 선행 검색에 대해 언급하나? 만약 그것에 차이가 없다면? 그리고 그것을 건너 띄어서 전처리기를 좀 더 빠르게 만드는 것은 어떤가?" 대답은 선행 검색은 세 가지 특별한 경우에 차이점을 만든다는 것이다.

We say that nested calls to a macro occur when a macro's argument contains a call to that very macro. For example, if `f' is a macro that expects one argument, `f (f (1))' is a nested pair of calls to `f'. The desired expansion is made by expanding `f (1)' and substituting that into the definition of `f'. The prescan causes the expected result to happen. Without the prescan, `f (1)' itself would be substituted as an argument, and the inner use of `f' would appear during the main scan as an indirect self-reference and would not be expanded. Here, the prescan cancels an undesirable side effect (in the medical, not computational, sense of the term) of the special rule for self-referential macros.

우리는 중첩은 매크로의 인자들로 매크로를 호출 할 때 발생하는 매크로라고 부른다. 예를 들어, 만약 `f'가 하나의 예상 할 수 있는 매크로라면, `f (f (1))'는 `f에 중첩 호출 쌍이다. 바람직한 확장은 `f(1)확장과 `f’의 정의로 대체함으로써 만들어 진다. 선행 검색은 예상된 결과를 발생 시킨다. 선행 검색이 없다면, `f(1)’은 그것 자체가 인자로써 대체 될 것이고 `f’의 내적 사용은 메인 검색 동안에 간접적인 자기 참조로써 나타날지 모르고 확장 되지 않을 것이다. 선행 검색은 자기 참조 매크로들을 위한 특별한 룰의 바람직하지 않은 부가적 효과를 취소 시킨다.

Prescan causes trouble in certain other cases of nested macro calls. Here is an example:

선행검색은 중첩된 매크로 호출의 어떤 다른 경우에 문제를 야기 시킨다. 예를 봐라

#define foo  a,b
#define bar(x) lose(x)
#define lose(x) (1 + (x))

bar(foo)

We would like `bar(foo)' to turn into `(1 + (foo))', which would then turn into `(1 + (a,b))'. Instead, `bar(foo)' expands into `lose(a,b)', and you get an error because lose requires a single argument. In this case, the problem is easily solved by the same parentheses that ought to be used to prevent misnesting of arithmetic operations:

우리는 `bar(foo)`를 `(1 + (foo))' 바꾸기를 원한다. 그리고 다음에 `(1 + (a,b))'하기를 원한다. 대신에, `bar(foo)’는 `lose(a,b)'로 확장 된다. 그리고 당신은 하나의 인자 요구를 잃었기 때문에 에러를 얻게 된다. 이 경우, 수학적 연산의 잘못된 중첩을 방지하기 위해서 같은 괄호를 사용함으로써 쉽게 문제는 해결 된다.

 

#define foo (a,b)
#define bar(x) lose((x))

The problem is more serious when the operands of the macro are not expressions; for example, when they are statements. Then parentheses are unacceptable because they would make for invalid C code:

매크로의 피연자들이 표현이 아닐 때 문제는 더 심각해진다.; 예를 들면 그것들이 문장둘일 때이다. 그 다음에 괄호들은 받아 들일 수 없다. 왜냐하면 그것은 C 코드를 올바르지 않게 만들기 때문이다.

#define foo { int a, b; ... }

In GNU C you can shield the commas using the `({...})' construct which turns a compound statement into an expression:

GNU C에서 당신은  복잡한 문자을 표현식으로 바꾸는 `({...})’구조를 사용해서 콤마들을 보호할 수 있다.

#define foo ({ int a, b; ... })

Or you can rewrite the macro definition to avoid such commas:

또는 당신은 매크로 정의를 그런 콤마를 피해서 다시 쓸 수 있다.

#define foo { int a; int b; ... }

There is also one case where prescan is useful. It is possible to use prescan to expand an argument and then stringify it -- if you use two levels of macros. Let's add a new macro `xstr' to the example shown above:

선행 검색이 유용한 곳이 또 한 경우가 있다. 인자를 확장하고 stringify하는 것에 선행처리를 사용하는 것이 가능하다 - 만약 당신이 매크로들의 두 레벨을 사용한다면. 새로운 매크로 `xstr'를 위의 예에 더해 보자.

#define xstr(s) str(s)
#define str(s) #s
#define foo 4
xstr (foo)

This expands into `"4"', not `"foo"'. The reason for the difference is that the argument of `xstr' is expanded at prescan (because `xstr' does not specify stringification or concatenation of the argument). The result of prescan then forms the argument for `str'. `str' uses its argument without prescan because it performs stringification; but it cannot prevent or undo the prescanning already done by `xstr'.

이 확장은 `"foo"'가 아니라 `"4"'로 확장 된다. 차이점에 이유는 `xstr`의 인자는 선행검색에서 확장된 것이 때문이다( 왜냐하면 `xstr’은 인자의stringification 또는 concatenation을 구체화하지 않기 때문이다.). 선행 검색의 결과는 `str’을 위한 인자로 형식화 된다. `str’은 선행 검색 없이 그것의 인자를 사용한다. 왜냐하면 그것은 stringfication을 수행하기 때문이다; 그러나 `xstr’로 이미 끝낸 선행검색 하는 것을 되돌리거나 막을 수는 없다.

Cascaded Use of Macros

A cascade of macros is when one macro's body contains a reference to another macro. This is very common practice. For example,

매크로의cascade는 한 매크로의 몸채가 다른 매크로에 참조를 포함할 때 이다. 이것은 매우 흔한 연습이다. 예를 보면,

#define BUFSIZE 1020
#define TABLESIZE BUFSIZE

This is not at all the same as defining `TABLESIZE' to be `1020'. The `#define' for `TABLESIZE' uses exactly the body you specify -- in this case, `BUFSIZE' -- and does not check to see whether it too is the name of a macro.

이것은 'TABLESIZE'를 `1020'로 되게 정의 하는 것과 전혀 같지 않다. `TABLESIZE'을 위한 `#define’는 정확하게 당신이 구체화한 몸체에 사용한다?이 경우, `BUFSIZE’?그리고 그것이 매크로의 이름인지 아닌지 보기위해 체크하지 않는다

It's only when you use `TABLESIZE' that the result of its expansion is checked for more macro names.

확장의 결과가 좀더 매크로 이름들을 위해 체크되는 것은 당신이 `TABLESIZE'를 사용할 때 만이다

This makes a difference if you change the definition of `BUFSIZE' at some point in the source file. `TABLESIZE', defined as shown, will always expand using the definition of `BUFSIZE' that is currently in effect:

만약 당신이  소스 파일의 같은 지점에서 `BUFSIZE'의 정의를 바꾼다면 이것은 차이점을 만들다.`TABLESIZE'는 항상 현재 효력을 갖고 있는`BUFSIZE'의 정의를 이용해서 확장할 것이다.

#define BUFSIZE 1020
#define TABLESIZE BUFSIZE
#undef BUFSIZE
#define BUFSIZE 37

Now `TABLESIZE' expands (in two stages) to `37'. (The `#undef' is to prevent any warning about the nontrivial redefinition of BUFSIZE.)

지금 `TABLESIZE'는 ( 둘째 단계에서) `37'로 확장 된다. ( `#undef' 는 BUFSIZE의 하찮지 않은 재정의에 대한 어떤 경고도 방지할 수 있다.)

Newlines in Macro Arguments

The invocation of a function-like macro can extend over many logical lines. The ISO C standard requires that newlines within a macro invocation be treated as ordinary whitespace. This means that when the expansion of a function-like macro replaces its invocation, it appears on the same line as the macro name did. Thus line numbers emitted by the compiler or debugger refer to the line the invocation started on, which might be different to the line containing the argument causing the problem.

function-like 매크로의 소환은 많은 논리 라인들을 확장한다. ISO C 표준은 매크로 소환 내에서 새로운 라인들은 보통 공백으로써 다루도록 요구 한다. 이것이 의미하는 것은 fuction-like 매크로의 확장은 그것의 소환을 교체할 때, 매크로 이름이 하는 것처럼 같은 라인에 나타난다는 것이다. 게다가 라인의 넘버들은 컴파일러나 디버거가 소환이 시작하는 라인을 생각하는 것을 허용한다. 그리고 문제를 야기하는 인자들을 포함한 라인과의 차이가 될 것이다.

Here is an example illustrating this:

여기 설명하는 예가 있다.:

#define ignore_second_arg(a,b,c) a; c

ignore_second_arg (foo (),
                   ignored (),
                   syntax error);

The syntax error triggered by the tokens `syntax error' results in an error message citing line three -- the line of ignore_second_arg --- even though the problematic code comes from line five.

`sytax error' 토큰에 의해 시작된 이 문법 에러는 라인 5에 문제 코드가 있어도  라인 3( ignore_second_arg에 라인 )에서 보고된 에러 메시지를 결과로 낸다.

Conditionals

In a macro processor, a conditional is a directive that allows a part of the program to be ignored during compilation, on some conditions. In the C preprocessor, a conditional can test either an arithmetic expression or whether a name is defined as a macro.

A conditional in the C preprocessor resembles in some ways an `if' statement in C, but it is important to understand the difference between them. The condition in an `if' statement is tested during the execution of your program. Its purpose is to allow your program to behave differently from run to run, depending on the data it is operating on. The condition in a preprocessing conditional directive is tested when your program is compiled. Its purpose is to allow different code to be included in the program depending on the situation at the time of compilation.

Why Conditionals are Used

Generally there are three kinds of reason to use a conditional.

Most simple programs that are intended to run on only one machine will not need to use preprocessing conditionals.

Syntax of Conditionals

A conditional in the C preprocessor begins with a conditional directive: `#if', `#ifdef' or `#ifndef'. See section Conditionals and Macros, for information on `#ifdef' and `#ifndef'; only `#if' is explained here.

The `#if' Directive

The `#if' directive in its simplest form consists of

#if expression
controlled text
#endif /* expression */

The comment following the `#endif' is not required, but it is a good practice because it helps people match the `#endif' to the corresponding `#if'. Such comments should always be used, except in short conditionals that are not nested. In fact, you can put anything at all after the `#endif' and it will be ignored by the GNU C preprocessor, but only comments are acceptable in ISO Standard C.

expression is a C expression of integer type, subject to stringent restrictions. It may contain

Note that `sizeof' operators and enum-type values are not allowed. enum-type values, like all other identifiers that are not taken as macro calls and expanded, are treated as zero.

The controlled text inside of a conditional can include preprocessing directives. Then the directives inside the conditional are obeyed only if that branch of the conditional succeeds. The text can also contain other conditional groups. However, the `#if' and `#endif' directives must balance.

The `#else' Directive

The `#else' directive can be added to a conditional to provide alternative text to be used if the condition is false. This is what it looks like:

#if expression
text-if-true
#else /* Not expression */
text-if-false
#endif /* Not expression */

If expression is nonzero, and thus the text-if-true is active, then `#else' acts like a failing conditional and the text-if-false is ignored. Conversely, if the `#if' conditional fails, the text-if-false is considered included.

The `#elif' Directive

One common case of nested conditionals is used to check for more than two possible alternatives. For example, you might have

#if X == 1
...
#else /* X != 1 */
#if X == 2
...
#else /* X != 2 */
...
#endif /* X != 2 */
#endif /* X != 1 */

Another conditional directive, `#elif', allows this to be abbreviated as follows:

#if X == 1
...
#elif X == 2
...
#else /* X != 2 and X != 1*/
...
#endif /* X != 2 and X != 1*/

`#elif' stands for "else if". Like `#else', it goes in the middle of a `#if'-`#endif' pair and subdivides it; it does not require a matching `#endif' of its own. Like `#if', the `#elif' directive includes an expression to be tested.

The text following the `#elif' is processed only if the original `#if'-condition failed and the `#elif' condition succeeds. More than one `#elif' can go in the same `#if'-`#endif' group. Then the text after each `#elif' is processed only if the `#elif' condition succeeds after the original `#if' and any previous `#elif' directives within it have failed. `#else' is equivalent to `#elif 1', and `#else' is allowed after any number of `#elif' directives, but `#elif' may not follow `#else'.

Keeping Deleted Code for Future Reference

If you replace or delete a part of the program but want to keep the old code around as a comment for future reference, the easy way to do this is to put `#if 0' before it and `#endif' after it. This is better than using comment delimiters `/*' and `*/' since those won't work if the code already contains comments (C comments do not nest).

This works even if the code being turned off contains conditionals, but they must be entire conditionals (balanced `#if' and `#endif').

Conversely, do not use `#if 0' for comments which are not C code. Use the comment delimiters `/*' and `*/' instead. The interior of `#if 0' must consist of complete tokens; in particular, single-quote characters must balance. Comments often contain unbalanced single-quote characters (known in English as apostrophes). These confuse `#if 0'. They do not confuse `/*'.

Conditionals and Macros

Conditionals are useful in connection with macros or assertions, because those are the only ways that an expression's value can vary from one compilation to another. A `#if' directive whose expression uses no macros or assertions is equivalent to `#if 1' or `#if 0'; you might as well determine which one, by computing the value of the expression yourself, and then simplify the program.

For example, here is a conditional that tests the expression `BUFSIZE == 1020', where `BUFSIZE' must be a macro.

#if BUFSIZE == 1020
  printf ("Large buffers!\n");
#endif /* BUFSIZE is large */

(Programmers often wish they could test the size of a variable or data type in `#if', but this does not work. The preprocessor does not understand sizeof, or typedef names, or even the type keywords such as int.)

The special operator `defined' is used in `#if' and `#elif' expressions to test whether a certain name is defined as a macro. Either `defined name' or `defined (name)' is an expression whose value is 1 if name is defined as macro at the current point in the program, and 0 otherwise. To the `defined' operator it makes no difference what the definition of the macro is; all that matters is whether there is a definition. Thus, for example,

#if defined (vax) || defined (ns16000)

would succeed if either of the names `vax' and `ns16000' is defined as a macro. You can test the same condition using assertions (see section Assertions), like this:

#if #cpu (vax) || #cpu (ns16000)

If a macro is defined and later undefined with `#undef', subsequent use of the `defined' operator returns 0, because the name is no longer defined. If the macro is defined again with another `#define', `defined' will recommence returning 1.

If the `defined' operator appears as a result of a macro expansion, the C standard says the behavior is undefined. GNU cpp treats it as a genuine `defined' operator and evaluates it normally. It will warn wherever your code uses this feature if you use the command-line option `-pedantic', since other compilers may handle it differently.

Conditionals that test whether a single macro is defined are very common, so there are two special short conditional directives for this case.

#ifdef name
is equivalent to `#if defined (name)'.
#ifndef name
is equivalent to `#if ! defined (name)'.

Macro definitions can vary between compilations for several reasons.

The `#error' and `#warning' Directives

The directive `#error' causes the preprocessor to report a fatal error. The tokens forming the rest of the line following `#error' are used as the error message, and not macro-expanded. Internal whitespace sequences are each replaced with a single space. The line must consist of complete tokens.

You would use `#error' inside of a conditional that detects a combination of parameters which you know the program does not properly support. For example, if you know that the program will not run properly on a Vax, you might write

#ifdef __vax__
#error "Won't work on Vaxen.  See comments at get_last_object."
#endif

See section Nonstandard Predefined Macros, for why this works.

If you have several configuration parameters that must be set up by the installation in a consistent way, you can use conditionals to detect an inconsistency and report it with `#error'. For example,

#if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
    || HASH_TABLE_SIZE % 5 == 0
#error HASH_TABLE_SIZE should not be divisible by a small prime
#endif

The directive `#warning' is like the directive `#error', but causes the preprocessor to issue a warning and continue preprocessing. The tokens following `#warning' are used as the warning message, and not macro-expanded.

You might use `#warning' in obsolete header files, with a message directing the user to the header file which should be used instead.

Assertions

Assertions are a more systematic alternative to macros in writing conditionals to test what sort of computer or system the compiled program will run on. Assertions are usually predefined, but you can define them with preprocessing directives or command-line options.

The macros traditionally used to describe the type of target are not classified in any way according to which question they answer; they may indicate a hardware architecture, a particular hardware model, an operating system, a particular version of an operating system, or specific configuration options. These are jumbled together in a single namespace. In contrast, each assertion consists of a named question and an answer. The question is usually called the predicate. An assertion looks like this:

#predicate (answer)

You must use a properly formed identifier for predicate. The value of answer can be any sequence of words; all characters are significant except for leading and trailing whitespace, and differences in internal whitespace sequences are ignored. (This is similar to the rules governing macro redefinition.) Thus, `x + y' is different from `x+y' but equivalent to ` x + y '. `)' is not allowed in an answer.

Here is a conditional to test whether the answer answer is asserted for the predicate predicate:

#if #predicate (answer)

There may be more than one answer asserted for a given predicate. If you omit the answer, you can test whether any answer is asserted for predicate:

#if #predicate

Most of the time, the assertions you test will be predefined assertions. GNU C provides three predefined predicates: system, cpu, and machine. system is for assertions about the type of software, cpu describes the type of computer architecture, and machine gives more information about the computer. For example, on a GNU system, the following assertions would be true:

#system (gnu)
#system (mach)
#system (mach 3)
#system (mach 3.subversion)
#system (hurd)
#system (hurd version)

and perhaps others. The alternatives with more or less version information let you ask more or less detailed questions about the type of system software.

On a Unix system, you would find #system (unix) and perhaps one of: #system (aix), #system (bsd), #system (hpux), #system (lynx), #system (mach), #system (posix), #system (svr3), #system (svr4), or #system (xpg4) with possible version numbers following.

Other values for system are #system (mvs) and #system (vms).

Portability note: Many Unix C compilers provide only one answer for the system assertion: #system (unix), if they support assertions at all. This is less than useful.

An assertion with a multi-word answer is completely different from several assertions with individual single-word answers. For example, the presence of system (mach 3.0) does not mean that system (3.0) is true. It also does not directly imply system (mach), but in GNU C, that last will normally be asserted as well.

The current list of possible assertion values for cpu is: #cpu (a29k), #cpu (alpha), #cpu (arm), #cpu (clipper), #cpu (convex), #cpu (elxsi), #cpu (tron), #cpu (h8300), #cpu (i370), #cpu (i386), #cpu (i860), #cpu (i960), #cpu (m68k), #cpu (m88k), #cpu (mips), #cpu (ns32k), #cpu (hppa), #cpu (pyr), #cpu (ibm032), #cpu (rs6000), #cpu (sh), #cpu (sparc), #cpu (spur), #cpu (tahoe), #cpu (vax), #cpu (we32000).

You can create assertions within a C program using `#assert', like this:

#assert predicate (answer)

(Note the absence of a `#' before predicate.)

Each time you do this, you assert a new true answer for predicate. Asserting one answer does not invalidate previously asserted answers; they all remain true. The only way to remove an answer is with `#unassert'. `#unassert' has the same syntax as `#assert'. You can also remove all answers to a predicate like this:

#unassert predicate

You can also add or cancel assertions using command options when you run gcc or cpp. See section Invoking the C Preprocessor.

Combining Source Files

One of the jobs of the C preprocessor is to inform the C compiler of where each line of C code came from: which source file and which line number.

C code can come from multiple source files if you use `#include'; both `#include' and the use of conditionals and macros can cause the line number of a line in the preprocessor output to be different from the line's number in the original source file. You will appreciate the value of making both the C compiler (in error messages) and symbolic debuggers such as GDB use the line numbers in your source file.

The C preprocessor builds on this feature by offering a directive by which you can control the feature explicitly. This is useful when a file for input to the C preprocessor is the output from another program such as the bison parser generator, which operates on another file that is the true source file. Parts of the output from bison are generated from scratch, other parts come from a standard parser file. The rest are copied nearly verbatim from the source file, but their line numbers in the bison output are not the same as their original line numbers. Naturally you would like compiler error messages and symbolic debuggers to know the original source file and line number of each line in the bison input.

bison arranges this by writing `#line' directives into the output file. `#line' is a directive that specifies the original line number and source file name for subsequent input in the current preprocessor input file. `#line' has three variants:

#line linenum
Here linenum is a decimal integer constant. This specifies that the line number of the following line of input, in its original source file, was linenum.
#line linenum filename
Here linenum is a decimal integer constant and filename is a string constant. This specifies that the following line of input came originally from source file filename and its line number there was linenum. Keep in mind that filename is not just a file name; it is surrounded by double-quote characters so that it looks like a string constant.
#line anything else
anything else is checked for macro calls, which are expanded. The result should be a decimal integer constant followed optionally by a string constant, as described above.

`#line' directives alter the results of the `__FILE__' and `__LINE__' predefined macros from that point on. See section Standard Predefined Macros.

The output of the preprocessor (which is the input for the rest of the compiler) contains directives that look much like `#line' directives. They start with just `#' instead of `#line', but this is followed by a line number and file name as in `#line'. See section C Preprocessor Output.

Miscellaneous Preprocessing Directives

This section describes some additional, rarely used, preprocessing directives.

The ISO standard specifies that the effect of the `#pragma' directive is implementation-defined. The GNU C preprocessor recognizes some pragmas, and passes unrecognized ones through to the preprocessor output, so they are available to the compilation pass.

In line with the C99 standard, which introduces a STDC namespace for C99 pragmas, the preprocessor introduces a GCC namespace for GCC pragmas. Supported GCC preprocessor pragmas are of the form `#pragma GCC ...'. For backwards compatibility previously supported pragmas are also recognized without the `GCC' prefix, however that use is deprecated. Pragmas that are already deprecated are not recognized with a `GCC' prefix.

The `#pragma GCC dependency' allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the include file is derived from the other file, and should be regenerated. The other file is searched for using the normal include search path. Optional trailing text can be used to give more information in the warning message.

#pragma GCC dependency "parse.y"
#pragma GCC dependency "/usr/include/time.h" rerun /path/to/fixincludes

The C99 standard also introduces the `_Pragma' operator. The syntax is _Pragma (string-literal), where `string-literal' can be either a normal or wide-character string literal. It is destringized, by replacing all `\\' with a single `\' and all `\"' with a `"'. The result is then processed as if it had appeared as the right hand side of a `#pragma' directive. For example,

_Pragma ("GCC dependency \"parse.y\"")

has the same effect as `#pragma GCC dependency "parse.y"'. The same effect could be achieved using macros, for example

#define DO_PRAGMA(x) _Pragma (#x)
DO_PRAGMA (GCC dependency "parse.y")

The standard is unclear on where a `_Pragma' operator can appear. The preprocessor accepts it even within a preprocessing conditional directive like `#if'. To be safe, you are probably best keeping it out of directives other than `#define', and putting it on a line of its own.

The `#ident' directive is supported for compatibility with certain other systems. It is followed by a line of text. On some systems, the text is copied into a special place in the object file; on most systems, the text is ignored and this directive has no effect. Typically `#ident' is only used in header files supplied with those systems where it is meaningful.

The null directive consists of a `#' followed by a newline, with only whitespace (including comments) in between. A null directive is understood as a preprocessing directive but has no effect on the preprocessor output. The primary significance of the existence of the null directive is that an input line consisting of just a `#' will produce no output, rather than a line of output containing just a `#'. Supposedly some old C programs contain such lines.

C Preprocessor Output

The output from the C preprocessor looks much like the input, except that all preprocessing directive lines have been replaced with blank lines and all comments with spaces.

The ISO standard specifies that it is implementation defined whether a preprocessor preserves whitespace between tokens, or replaces it with e.g. a single space. In the GNU C preprocessor, whitespace between tokens is collapsed to become a single space, with the exception that the first token on a non-directive line is preceded with sufficient spaces that it appears in the same column in the preprocessed output that it appeared in in the original source file. This is so the output is easy to read. See section Undefined Behavior and Deprecated Features.

Source file name and line number information is conveyed by lines of the form

# linenum filename flags

which are inserted as needed into the output (but never within a string or character constant), and in place of long sequences of empty lines. Such a line means that the following line originated in file filename at line linenum.

After the file name comes zero or more flags, which are `1', `2', `3', or `4'. If there are multiple flags, spaces separate them. Here is what the flags mean:

`1'
This indicates the start of a new file.
`2'
This indicates returning to a file (after having included another file).
`3'
This indicates that the following text comes from a system header file, so certain warnings should be suppressed.
`4'
This indicates that the following text should be treated as C.

Implementation-defined Behavior and Implementation Limits

The ISO C standard mandates that implementations document various aspects of preprocessor behavior. You should try to avoid undue reliance on behaviour described here, as it is possible that it will change subtly in future implementations.

The following documents internal limits of GNU cpp.

Undefined Behavior and Deprecated Features

This section details GNU C preprocessor behavior that is subject to change or deprecated. You are strongly advised to write your software so it does not rely on anything described here; future versions of the preprocessor may subtly change such behavior or even remove the feature altogether.

Preservation of the form of whitespace between tokens is unlikely to change from current behavior (section C Preprocessor Output), but you are advised not to rely on it.

The following are undocumented and subject to change:-

The following features are in flux and should not be used in portable code:

The following features are deprecated and will likely be removed at some point in the future:-

Invoking the C Preprocessor

Most often when you use the C preprocessor you will not have to invoke it explicitly: the C compiler will do so automatically. However, the preprocessor is sometimes useful on its own.

The C preprocessor expects two file names as arguments, infile and outfile. The preprocessor reads infile together with any other files it specifies with `#include'. All the output generated by the combined input files is written in outfile.

Either infile or outfile may be `-', which as infile means to read from standard input and as outfile means to write to standard output. Also, if either file is omitted, it means the same as if `-' had been specified for that file.

Here is a table of command options accepted by the C preprocessor. These options can also be given when compiling a C program; they are passed along automatically to the preprocessor when it is invoked by the compiler.

`-P'
Inhibit generation of `#'-lines with line-number information in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code and will be sent to a program which might be confused by the `#'-lines. See section C Preprocessor Output.
`-C'
Do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive. Comments appearing in the expansion list of a macro will be preserved, and appear in place wherever the macro is invoked. You should be prepared for side effects when using `-C'; it causes the preprocessor to treat comments as tokens in their own right. For example, macro redefinitions that were trivial when comments were replaced by a single space might become significant when comments are retained. Also, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a `#'.
`-traditional'
Try to imitate the behavior of old-fashioned C, as opposed to ISO C. Use the `-traditional' option when preprocessing Fortran code, so that single-quotes and double-quotes within Fortran comment lines (which are generally not recognized as such by the preprocessor) do not cause diagnostics about unterminated character or string constants. However, this option does not prevent diagnostics about unterminated comments when a C-style comment appears to start, but not end, within Fortran-style commentary. So, the following Fortran comment lines are accepted with `-traditional':
C This isn't an unterminated character constant
C Neither is "20000000000, an octal constant
C in some dialects of Fortran
However, this type of comment line will likely produce a diagnostic, or at least unexpected output from the preprocessor, due to the unterminated comment:
C Some Fortran compilers accept /* as starting
C an inline comment.
Note that g77 automatically supplies the `-traditional' option when it invokes the preprocessor. However, a future version of g77 might use a different, more-Fortran-aware preprocessor in place of cpp.
`-trigraphs'
Process ISO standard trigraph sequences. These are three-character sequences, all starting with `??', that are defined by ISO C to stand for single characters. For example, `??/' stands for `\', so `'??/n'' is a character constant for a newline. By default, GCC ignores trigraphs, but in standard-conforming modes it converts them. See the `-std' option. The nine trigraph sequences are
`??('
-> `['
`??)'
-> `]'
`??<'
-> `{'
`??>'
-> `}'
`??='
-> `#'
`??/'
-> `\'
`??''
-> `^'
`??!'
-> `|'
`??-'
-> `~'
Trigraph support is not popular, so many compilers do not implement it properly. Portable code should not rely on trigraphs being either converted or ignored.
`-pedantic'
Issue warnings required by the ISO C standard in certain cases such as when text other than a comment follows `#else' or `#endif'.
`-pedantic-errors'
Like `-pedantic', except that errors are produced rather than warnings.
`-Wcomment'
`-Wcomments'
(Both forms have the same effect). Warn whenever a comment-start sequence `/*' appears in a `/*' comment, or whenever a backslash-newline appears in a `//' comment.
`-Wtrigraphs'
Warn if any trigraphs are encountered. This option used to take effect only if `-trigraphs' was also specified, but now works independently. Warnings are not given for trigraphs within comments, as we feel this is obnoxious.
`-Wwhite-space'
Warn about possible white space confusion, e.g. white space between a backslash and a newline.
`-Wall'
Requests `-Wcomment', `-Wtrigraphs', and `-Wwhite-space' (but not `-Wtraditional' or `-Wundef').
`-Wtraditional'
Warn about certain constructs that behave differently in traditional and ISO C.
`-Wundef'
Warn if an undefined identifier is evaluated in an `#if' directive.
`-I directory'
Add the directory directory to the head of the list of directories to be searched for header files (see section The `#include' Directive). This can be used to override a system header file, substituting your own version, since these directories are searched before the system header file directories. If you use more than one `-I' option, the directories are scanned in left-to-right order; the standard system directories come after.
`-I-'
Any directories specified with `-I' options before the `-I-' option are searched only for the case of `#include "file"'; they are not searched for `#include <file>'. If additional directories are specified with `-I' options after the `-I-', these directories are searched for all `#include' directives. In addition, the `-I-' option inhibits the use of the current directory as the first search directory for `#include "file"'. Therefore, the current directory is searched only if it is requested explicitly with `-I.'. Specifying both `-I-' and `-I.' allows you to control precisely which directories are searched before the current one and which are searched after.
`-nostdinc'
Do not search the standard system directories for header files. Only the directories you have specified with `-I' options (and the current directory, if appropriate) are searched.
`-nostdinc++'
Do not search for header files in the C++-specific standard directories, but do still search the other standard directories. (This option is used when building the C++ library.)
`-remap'
When searching for a header file in a directory, remap file names if a file named `header.gcc' exists in that directory. This can be used to work around limitations of file systems with file name restrictions. The `header.gcc' file should contain a series of lines with two tokens on each line: the first token is the name to map, and the second token is the actual name to use.
`-D name'
Predefine name as a macro, with definition `1'.
`-D name=definition'
Predefine name as a macro, with definition definition. There are no restrictions on the contents of definition, but if you are invoking the preprocessor from a shell or shell-like program you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. If you use more than one `-D' for the same name, the rightmost definition takes effect.
`-U name'
Do not predefine name. If both `-U' and `-D' are specified for one name, whichever one appears later on the command line wins.
`-undef'
Do not predefine any nonstandard macros.
`-gcc'
Define the macros __GNUC__, __GNUC_MINOR__ and __GNUC_PATCHLEVEL__. These are defined automatically when you use `gcc -E'; you can turn them off in that case with `-no-gcc'.
`-A predicate=answer'
Make an assertion with the predicate predicate and answer answer. This form is preferred to the older form `-A predicate(answer)', which is still supported, because it does not use shell special characters. See section Assertions.
`-A -predicate=answer'
Disable an assertion with the predicate predicate and answer answer. Specifying no predicate, by `-A-' or `-A -', disables all predefined assertions and all assertions preceding it on the command line; and also undefines all predefined macros and all macros preceding it on the command line.
`-dM'
Instead of outputting the result of preprocessing, output a list of `#define' directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor; assuming you have no file `foo.h', the command
touch foo.h; cpp -dM foo.h
will show the values of any predefined macros.
`-dD'
Like `-dM' except in two respects: it does not include the predefined macros, and it outputs both the `#define' directives and the result of preprocessing. Both kinds of output go to the standard output file.
`-dN'
Like `-dD', but emit only the macro names, not their expansions.
`-dI'
Output `#include' directives in addition to the result of preprocessing.
`-M [-MG]'
Instead of outputting the result of preprocessing, output a rule suitable for make describing the dependencies of the main source file. The preprocessor outputs one make rule containing the object file name for that source file, a colon, and the names of all the included files. If there are many included files then the rule is split into several lines using `\'-newline. `-MG' says to treat missing header files as generated files and assume they live in the same directory as the source file. It must be specified in addition to `-M'. This feature is used in automatic updating of makefiles.
`-MM [-MG]'
Like `-M' but mention only the files included with `#include "file"'. System header files included with `#include <file>' are omitted.
`-MD file'
Like `-M' but the dependency information is written to file. This is in addition to compiling the file as specified -- `-MD' does not inhibit ordinary compilation the way `-M' does. When invoking gcc, do not specify the file argument. gcc will create file names made by replacing ".c" with ".d" at the end of the input file names. In Mach, you can use the utility md to merge multiple dependency files into a single dependency file suitable for using with the `make' command.
`-MMD file'
Like `-MD' except mention only user header files, not system header files.
`-H'
Print the name of each header file used, in addition to other normal activities.
`-imacros file'
Process file as input, discarding the resulting output, before processing the regular input file. Because the output generated from file is discarded, the only effect of `-imacros file' is to make the macros defined in file available for use in the main input.
`-include file'
Process file as input, and include all the resulting output, before processing the regular input file.
`-idirafter dir'
Add the directory dir to the second include path. The directories on the second include path are searched when a header file is not found in any of the directories in the main include path (the one that `-I' adds to).
`-iprefix prefix'
Specify prefix as the prefix for subsequent `-iwithprefix' options. If the prefix represents a directory, you should include the final `/'.
`-iwithprefix dir'
Add a directory to the second include path. The directory's name is made by concatenating prefix and dir, where prefix was specified previously with `-iprefix'.
`-isystem dir'
Add a directory to the beginning of the second include path, marking it as a system directory, so that it gets the same special treatment as is applied to the standard system directories. See section System Headers.
`-x c'
`-x c++'
`-x objective-c'
`-x assembler-with-cpp'
Specify the source language: C, C++, Objective-C, or assembly. This has nothing to do with standards conformance or extensions; it merely selects which base syntax to expect. If you give none of these options, cpp will deduce the language from the extension of the source file: `.c', `.cc', `.m', or `.S'. Some other common extensions for C++ and assembly are also recognized. If cpp does not recognize the extension, it will treat the file as C; this is the most generic mode. Note: Previous versions of cpp accepted a `-lang' option which selected both the language and the standards conformance level. This option has been removed, because it conflicts with the `-l' option.
`-std=standard'
`-ansi'
Specify the standard to which the code should conform. Currently cpp only knows about the standards for C; other language standards will be added in the future. standard may be one of:
iso9899:1990
c89
The ISO C standard from 1990. `c89' is the customary shorthand for this version of the standard. The `-ansi' option is equivalent to `-std=c89'.
iso9899:199409
The 1990 C standard, as amended in 1994.
iso9899:1999
c99
iso9899:199x
c9x
The revised ISO C standard, published in December 1999. Before publication, this was known as C9X.
gnu89
The 1990 C standard plus GNU extensions. This is the default.
gnu99
gnu9x
The 1999 C standard plus GNU extensions.
`-ftabstop=NUMBER'
Set the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. Values less than 1 or greater than 100 are ignored. The default is 8.
`-$'
Forbid the use of `$' in identifiers. The C standard allows implementations to define extra characters that can appear in identifiers. By default the GNU C preprocessor permits `$', a common extension.


Go to the first, previous, next, last section, table of contents.