Is this a good practice for positioning the header declarations?

Michael Tadyshak 80 Reputation points
2023-09-18T20:30:22.4166667+00:00

Is it good practice to include ONLY the header file for a class in the .cpp file and then put your list of includes in the class header file? For example:

// In file AddParms.cpp:

#include "AddParms.h"

AddParms::AddParms()

{

}

...

// In file AddParms.h:

#ifndef _ADDPARMSH

#define _ADDPARMSH

#include "pch.h"

#include <afxtempl.h> //For CList

#include <atlstr.h> //For CString

class AddParms

...

Is that a good placement for pch.h?

To setup pre-compiled headers, do you set all projects to /Yc for creating pre-compiled headers and build all projects? Then set all projects to /Yu for using pre-compiled headers then leave it that way?

(With certain constraints, which I have read about)

Developer technologies | C++
{count} votes

4 answers

Sort by: Most helpful
  1. Castorix31 90,686 Reputation points
    2023-09-18T20:49:54.59+00:00
    0 comments No comments

  2. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2023-09-19T06:56:54.1+00:00

    Hi, @Michael Tadyshak

    You need to add #include"pch.h" in source file(.cpp) instead of header file. Or you will get error C1010.
    User's image

    And as the document says,

    set only one file in your project to be compiled by using the /Yc option, and set all other files to compile by using the /Yu option.

    Set your project properties to /Yu , then set one specific file pch.cpp to /Yc. enter image description here

    Right Click pch.cpp > properties -> C/C++ -> Precomplied Headers

    User's image

    enter image description here

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. RLWA32 49,636 Reputation points
    2023-09-19T09:38:35.8266667+00:00

    In addition to the guidance previously provided I suggest that the #include statements for framework headers like afxtempl.h and atlstr.h be made part of the precompiled header since they are unchanging and it is less efficient to compile them with every build.

    0 comments No comments

  4. kwikc 136 Reputation points
    2023-09-23T08:28:51.8566667+00:00

    I would say it's not a good practice. I put #include for only required header files in .cpp files, and header files in .h files as less as possible. And I avoid using pre-compiled headers. If not obeying these rules, one day, a change to any header file can result in compiling the whole project.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.