Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm going to implement 'friend' classes in C! For this I need not to allow all sources to include specific header file. One method is to define the whole child class in the parent class. This is not a good idea, because the volume of the parent file increases and it seems that they're dependent. It also denies other classes (implemented in C, I mean) not to be able to access the child class, while I want also to be friends. Another method may be finding what source is including the header file (in the header file). If I find that the source is not what I (the header file) mean, I may issue and error with #error. You may say that I may #define something in the source file and check it in the header file whether it has been defined. But I want to prevent other sources from defining this. Knowing what source file has exactly included me (the header file) is a better idea. Is there a way for this purpose? The compiler I use is gcc 9.3.0 under Ubuntu 20.04.

What I have tried:

It's not a bug fix issue. I'm looking for others suggestions to find the best method for this purpose.
Posted
Updated 9-Feb-21 6:18am
v2

1 solution

It's not exactly clear what you are trying to do. It sounds like you don't want to use
C
//myHeader.hpp
#ifndef MYHEADER_H
#define MYHEADER_H
/* ... header info */
#endif // MY_HEADER_H

If that's the case, maybe #pragma once is what you're looking for? It's not quite as portable as using include guards, but it is supported by gcc, clang and MS-C, so it should be "as portable as needed".

Also, your issue description says you are implementing in 'C', but classes and friends are C++ items, and not available in C. If you are using C++, make sure you are compiling with g++!
 
Share this answer
 
Comments
ilostmyid2 9-Feb-21 13:02pm    
Oh man! I described why I'm hesitating to use this method.
k5054 9-Feb-21 13:18pm    
Did you read everything I wrote? I suggested using
#pragma once
rather than include guards. I don't see where in your issue description you say you have a problem with that suggestion.
ilostmyid2 9-Feb-21 13:25pm    
Yeah I did. Preventing a header file from being included again is not what I asked! Please re-read my question. In header file I need to know the name and path of the file which has included it. This is really a different thing.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900