Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C or C++ can I impose restrictions as to which files can include my header file

In C/C++ I have written a header file which is available to all, however I want to restrict the files that include it. Is there any way I can generate compiler error if my header files is included by an "unauthorized" c/cxx file?

like image 881
Aniruddha Avatar asked Apr 06 '16 16:04

Aniruddha


People also ask

Can you include header files in header files C?

Note: We can't include the same header file twice in any program. Create your own Header File: Instead of writing a large and complex code, we can create your own header files and include them in our program to use it whenever we want.

What happens when you include a header file in C?

It attempts to find a function definition (implementation), which exactly matches the header you declared earlier. What happens if you #include header file is that compiler (specifically, the preprocessor) copies the whole contents of header file into place, where you put your #include .

In which section of C program header files are included?

In C language, header files contain the set of predefined standard library functions. The “#include” preprocessing directive is used to include the header files with “. h” extension in the program.

Should header file include C file?

As others have noted, it helps ensure that the declarations in the header file are consistent with the definitions in the C file. This is of particular importance when some or all of the routines are to be called from another module. In other words, this can help cut down on errors.


1 Answers

Of course there is no proper security feature for this (that'd be plain silly), but what you could do is to produce an error in your header file if a certain macro is not present when including the file, so that your header.h starts with

#ifndef AUTHORIZED_TO_INCLUDE_THE_HEADER
#error "You're not authorized to include this file"
#endif

then in the files that include this, do

#define AUTHORIZED_TO_INCLUDE_THE_HEADER
#include "header.h"