Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick question regarding Conditional Compilation (ifndef)

This is quite probably a very silly question but I need to be sure. I've been given a class declaration in a header file eg.

#ifndef file_H
#define file_H

class ex{
private:

public:
};

#endif

and I've been required to write the method definitions in the same file, which I have done, my question is does the "#endif" stay where it is just after the class declaration or does it go at the end of my file after the class method definitions?.

like image 811
silent Avatar asked May 16 '10 04:05

silent


People also ask

How does conditional compilation help a programmer?

Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.

Why is conditional compilation used in C?

Conditional Compilation: Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions.

What is the difference between #ifdef and #ifndef?

The defined( identifier ) constant expression used with the #if directive is preferred. The #ifndef directive checks for the opposite of the condition checked by #ifdef . If the identifier hasn't been defined, or if its definition has been removed with #undef , the condition is true (nonzero).


1 Answers

At the end of the file.

The goal of this form of this #ifndef pattern is to prevent a situation where the same declaration or definition appears twice in a compilation unit.

This is done because a C file may include several H files, which somewhere up the chain may in turn include the same file. IF you simply ran the preprocessor without these, you would have multiple copies of the H file. This way, you have multiple copies, but the preprocessor ignores everything after the first encounter.

Since you're not supposed to be defining anything more than once, if you have to place method definitions in the header file, put them within the #endif.

like image 91
Uri Avatar answered Oct 12 '22 09:10

Uri