Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of _p.h files?

In Qt Source files, there are two versions of header files, such as:

qxmlstream.h
qxmlstream_p.h

Why are there _p.h files?

like image 809
metdos Avatar asked Jun 29 '10 11:06

metdos


2 Answers

They're generally private header files, used so that components of a subsystems know about everything but users don't need to.

In other words, something that multiple C source files in Qt might want to know about would be in the private header files if the users of Qt didn't need to know about them.

One example might be a customised memory allocator for your subsystem. Perhaps you know that every memory allocation you make is 128 bytes then you can provide such an allocator:

void * malloc128 (void) { ... }

Since this is likely to be of dubious value to users of your subsystem, there's no point publishing it as part of the official API but every single one of your own source files needs the prototype so you'd put it in the private header file.

Then your own code uses:

#include "mysubsystem_p.h"

while users of your API use:

#include "mysubsystem.h"
like image 92
paxdiablo Avatar answered Sep 28 '22 01:09

paxdiablo


Qt need to maintain stable external link-level interface. To solve that they use next approach:

class MyClass {
public:
  size_t compatSize();
private:
  MyClassPrivate *data;
};


// implementation
struct MyClassPrivate {
  int someFieldThatCanChange;
};
size_t compatSize() { return (size_t)(data->someFieldThatCanChange); }

By doing that change of implementation doesn't affect size and structure of MyClass. And you still able to add new fields or remove old one.
Other approach is to use "interfaces" (abstract classes), factories and virtual functions for every method - which will result in a slower code, I guess.

like image 20
ony Avatar answered Sep 28 '22 03:09

ony