Серебров Борис
Precompiled headers can dramatically increase compilation speeds ...
С++ Builder Language Guide
Вместо вступления сразу приведу пример. Полная сборка (build) проекта, содержащего около 170 cpp-модулей, при использовании предкомпилированных заголовков происходит за 811 секунд, при этом число обработанных компилятором строк составляет 1,808,780. При компиляции того же проекта без использования предкомпилированных заголовков, время сборки составляет 2399 секунд, а число строк, обработанных компилятором - 45,261,820. Впечатляет, не так ли? Плата за это ускорение, в принципе не велика - предкомпилированный образ, размер которого около 40 Мб.
При компиляции исходных текстов, компилятор должен обработать все *.cpp файлы проекта и все включенные в них *.h - файлы. При этом обрабатываются как пользовательские заголовочные файлы, так и стандартные, такие как vcl.h или Word2k.h. Количество кода, находящегося в стандартных заголовках может быть очень большим, например размер файла Word2k.h превышает 5 Мб, в нем больше 130 000 строк кода.
Так как содержимое стандартных заголовков не изменяется, то их компиляция при каждой сборке проекта является напрасной тратой времени. Предкомпилированные заголовки помогают решить эту проблему - стандартные файлы компилируются один раз, а затем используется скомпилированный двоичный образ.
Принцип действия предкомпилированных заголовков
Для управления предкомпилированными предназначена директива компилятора #pragma hdrstop. Все заголовочные файлы, включенные до этой директивы, помещаются в один образ, например:
#include <vcl.h>
#include <string>
#pragma hdrstop
Такая последовательность создаст образ, содержащий скомпилированные vcl.h и string. Этот образ будет использован для другого cpp-файла, если в нем до директивы hdrstop будут включены те же файлы, в том же порядке. Обращу внимание, что важен не только состав, но и порядок следования заголовков - даже если следующий cpp-файл включает те же заголовки, но сначала указан string, а потом vcl.h, то для этого cpp-файла будет создан новый образ.
Таким образом, для повторного использования предкомпилированного заголовка необходимо выполнение двух условий:
- состав включенный файлов до директивы hdrstop должен быть тем же
- последовательность включения файлов до директивы hdrstop должна быть той же
Сократить затраты на компиляцию стандартных заголовков до минимума можно только в том случае, если скомпилировать один образ, содержащий все стандартные заголовки, необходимые для проекта. Для этого нужно, чтобы:
- ВСЕ cpp-файлы проекта имели одинаковый блок включений до директивы hdrstop
- в этот блок должны входить ВСЕ стандартные заголовочные файлы, необходимые для проекта
Выполнить эти условия достаточно просто, для этого в начало каждого cpp-файла необходимо поместить следующие строки:
#include <pch.h>
#pragma hdrstop
где pch.h - файл, содержащий включения всех стандартных заголовков:
#ifndef PCH_H
#define PCH_H
#define INC_VCLDB_HEADERS
#define INC_VCLEXT_HEADERS
#include <vcl.h>
#include <sysset.h>
#include <IniFiles.hpp>
#include <AppEvnts.hpp>
#include <ActnMan.hpp>
...
#endif
Полный текст моей версии этого файла приведен в конце статьи. На h-файлы, входящие в предкомпилированный образ, накладывается ограничение - в них не должно быть инициализированных данных, например, в math.hpp есть строки:
static const Extended NaN = 0.0 / 0.0;
static const Extended Infinity = 1.0 / 0.0;
Из-за наличия этих констант включить math.hpp в файл pch.h нельзя.
Кстати, С++ Builder при добавлении новых модулей в проект реализует описанную стратегию управления предкомпилированными заголовками. Например, при создании нового приложения, файл Unit1.cpp будет таким:
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
....
Если посмотреть на текст vcl.h, то можно увидеть, что он является оболочкой для включения большого числа других стандартных заголовочных файлов.
Управлять составом включаемых в vcl.h заголовков можно с помощью специальных символов (INC_VCLDB_HEADERS, INC_VCLEXT_HEADERS и др.). В моей версии pch.h эти символы определяются с помощью #define до включения vcl.h, что приводит к увеличению числа включаемых файлов.
Как в существующем проекте перейти к использованию предкомпилированных заголовков
Даже в большом проекте перейти к использованию предкомпилированных заголовков достаточно просто.
В свойствах проекта нужно включить кэширование предкомпилированных заголовков и рекомендуется указать "персональный" файл, в котором будет храниться образ предкомпилированных заголовков: Project - Options - закладка Compiler, группа "Pre-compiled headers". Тут должно быть выбрано "Cache pre-compiled headers", а в поле "File Name" нужно ввести "pch.csm". При такой настройке образ с предкомпилированными заголовками будет находится в папке с проектом, в файле pch.csm.
После этого в начало каждого cpp-модуля необходимо вставить 2 строки:
#include "pch.h"
#pragma hdrstop
Все ранее включенные заголовочные файлы остаются на своих местах, их удалять не надо. Например:
#include "pch.h" // включает vcl.h, string и т.д.
#pragma hdrstop
#include <vcl.h>
#include <string>
...
Так как во всех стандартных заголовках применяются стражи повторного включения, то повторное их упоминание не влечет за собой повторного включения.
В принципе, при использовании pch.h, техническая потребность во включении стандартных заголовков исчезает. Однако, полезно все же указывать все необходимые для каждого конкретного модуля заголовки ниже директивы #pragma hdrstop. Во-первых, это в некоторой степени документирует модуль - по включаемым файлам можно судить, какими возможностями пользуется этот модуль. Во-вторых, это облегчает повторное использование модуля в других проектах, в которых либо не используется pch.h, либо его содержимое может быть другим.
Теоретически можно еще больше повысить эффективность компиляции, если включить в pch.h не только стандартные, но и все пользовательские заголовочные файлы. Практически, так как пользовательские заголовки меняются достаточно часто, это может повлечь за собой частую перекомпиляцию pch.h, что негативно скажется на времени компиляции. Кроме того, пользовательские заголовки обычно не бывают очень большими и компилируются очень быстро. Поэтому включать их pch.h не целесообразно.
Как проверить, что предкомпилированные заголовки используются эффективно
При добавлении в проект новых файлов нужно не забывать включать в них pch.h, иначе для них не будет использован общий предкомпилированный образ. Такая же ситуация может возникнуть, если в каком-то модуле включаются стандартные заголовки, которые не вошли в pch.h. Для того, чтобы отследить такие файлы, есть несколько способов:
- визуальное наблюдение за процессом компиляции. Обычно, число строк компилируемых в одном файле не должно превышать 10000-15000 строк
- если для проекта выбран индивидуальный файл для хранения образа предкомпилированных заголовков и этот файл называется pch.csm, то нужно обратить внимание на наличие вспомогательных файлов с именами pch.#00, pch.#01 и т.д. Если для всех файлов проекта используется один и тот же предкомпилированный образ, то вспомогательный файл должен быть только один - pch.#00. Если таких файлов больше, это значит что для каких-то cpp-модулей создаются дополнительные образы.
Текст pch.h
#ifndef PCH_H
#define PCH_H
#define INC_VCLDB_HEADERS
#define INC_VCLEXT_HEADERS
#include <vcl.h>
/* Все, что подключается предыдущими 3-мя строчками
// Core (minimal) Delphi RTL headers
#include <System.hpp>
#include <Types.hpp>
#include <Windows.hpp>
#include <Messages.hpp>
#include <SysUtils.hpp>
#include <Classes.hpp>
// Core (minimal) VCL headers
#if defined(INC_VCL)
#include <Controls.hpp>
#include <Graphics.hpp>
#include <Forms.hpp>
#include <Dialogs.hpp>
#include <StdCtrls.hpp>
#include <ExtCtrls.hpp>
// VCL Database related headers
#if defined(INC_VCLDB_HEADERS)
#include <DBCtrls.hpp>
#include <DB.hpp>
#include <DBTables.hpp>
#endif // INC_VCLDB_HEADERS
// Full set of VCL headers
#if defined(INC_VCLEXT_HEADERS)
#include <Buttons.hpp>
#include <ChartFX.hpp>
#include <ComCtrls.hpp>
#include <DBCGrids.hpp>
#include <DBGrids.hpp>
#include <DBLookup.hpp>
#include <DdeMan.hpp>
#include <FileCtrl.hpp>
#include <GraphSvr.hpp>
#include <Grids.hpp>
#include <MPlayer.hpp>
#include <Mask.hpp>
#include <Menus.hpp>
#include <OleCtnrs.hpp>
#include <OleCtrls.hpp>
#include <Outline.hpp>
#include <Tabnotbk.hpp>
#include <Tabs.hpp>
#include <VCFImprs.hpp>
#include <VCFrmla1.hpp>
#include <VCSpell3.hpp>
#endif // INC_VCLEXT_HEADERS
#endif // INC_VCL
*/
#include <sysset.h>
#include <IniFiles.hpp>
#include <AppEvnts.hpp>
#include <ActnMan.hpp>
#include <ActnCtrls.hpp>
#include <BandActn.hpp>
#include <CustomizeDlg.hpp>
#include <ImgList.hpp>
#include <ToolWin.hpp>
#include <ExtDlgs.hpp>
#include <ActnList.hpp>
#include <IBDatabase.hpp>
#include <IBCustomDataSet.hpp>
#include <IBQuery.hpp>
#include <IBTable.hpp>
#include <IBSQL.hpp>
#include <IBServices.hpp>
#include <math.h>
#include <assert.h>
#include <complex.h>
#include <values.h>
#include <map>
#include <list>
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
#include <memory>
#include <fstream>
//нестандартные компоненты RxLib и EhLib
#include "CURREDIT.hpp"
#include "RXSpin.hpp"
#include "RxCalc.hpp"
#include "RxCombos.hpp"
#include "APPUTILS.hpp"
#include "RXDBCtrl.hpp"
#include "Placemnt.hpp"
#include "DBGridEh.hpp"
#endif
Другие работы по теме:
Текст программы. 7 Используемые переменные. 7. Структура узла бинарного дерева. 7. Функция создания дерева. 7
Написать программу, читающую текст алгебраической формулы в инфиксной форме, включающей операции сложения, вычитания, умножения и деления, операнды (a, b, c, …, X, y, z) и круглые скобки
Разработка программы на четырех языках программирования
Этапы написания программы на четырех языках программирования (Turbo Pascal 7.0, Borland C++ 3.11, Delphi 7, Builder C++ 6.0), которая выводит на экран имя и фамилию студента, используя стандартные средства графики и простейшие геометрические фигуры.
Разработка визуальных компонентов для среды С++ Builder
C++ Builder - SDI-приложение, главное окно которого содержит настраиваемую инструментальную панель и палитру компонентов. Свойства атрибутов компонента, определяющие его внешний вид и поведение. События, методы и VCL компоненты в среде C++ Builder.
C++ Builder. Введение в структурное программирование
Создание консольных приложений с использованием графического интерфейса пользователя. Содержание палитры компонентов программы С++ Builder. Использование возможностей объектно-ориентированного программирования, особенности редактора кода и форм в С++.
Ввод вывод данных в дельфи
Ввод и вывод данных в среде Дельфи Дельфи представляет собой интегрированную среду разработки, инструменты которой позволяют значительно ускорить процесс разработки, создания и отладки программ.
Arnold
& Samson Essay, Research Paper Arnold Schwarzenegger: A Real Life Samson Heroes have been around since the beginning of time. The first hero that I can think of is David, from the biblical story David and Goliath. Heroes have not really evolved that much since the early days, they are still basically the same strong men with unhumanlike powers that the normal mortal man cannot even comprehend.
Arnold Schwarzenegger A Real Essay Research
Paper Bible as Literature Arnold Schwarzenegger: A Real Life Samson Heroes have been around since the beginning of time. The first hero that I can think of is David, from the biblical story David and Goliath. Heroes have not really evolved that much since the early days, they are still basically the same strong characters with inhuman like powers normal mortals can’t even comprehend.
James Jarome Hill Essay Research Paper James
James Jarome Hill Essay, Research Paper James Jarome Hill was born near Rockwood, Ontario in 1838. A boyhood accident that blinded him in one eye dashed his early dreams of becoming a doctor. He was forced to go to work at an early age due to the death of his father. At the age of 16, Hill went to St. Paul, Minnesota and took a job with a steamboat company.
Model Train Building And Computers Essay Research
Paper The world of Model Train Building has grown greatly with the aid of computers and technology to enhance the fun of building. Technology has long been a part of Model Train building with the adding of lights, bells, and whistles to capture your interest and imagination. But with the latest generation of building comes the influx of technology and the computer.
King Ramses II Essay Research Paper Ramses
King Ramses II Essay, Research Paper Ramses II Usermaatre Setepenre,third ruler of the 19th Dynasty,was born about 1303 B.C in the Eastern Nile Delta, following the death of his grandfather King Ramses I and Father Sethi I, was one of the longest reigning pharaohs of ancient Egypt.He reigned 67 years (roughly from 1290 to 1224 B.C), during the early part of his reign, Ramses fought to regain the territory in Africa and Western Asia that Egypt had held during the 15th and 16th centuries B.C in the beginning as coregent with his father, and lived for more than 80 years, which was very rare in those days.During his life he made quite a reputation as a builder and a warrior, but also as a ladies man.He had 5 or 6 main wives, mostly of all being Nefertari, but is known to have over 100 children with all of his wives.In Ancient Egypt people seems to have made fun of this fact.
The Convergence Of The Twain Essay Research
Paper The Titanic set sail for it’s maiden voyage on April 12,1912 . This beautiful ship was made of the strongest iron available to man during this time. The Titanic was believed to be the ship that even God could not sink. However, on April 14 tragedy stuck. Over 1,000 people were lost at sea when the titanic sank.
The Roles Of I330 And O90 Essay
, Research Paper The Roles of I-330 and O-90 Zamyatin s We is a story set far into the future. There is only one country, OneState, and the government controls everything. The story is actually a diary written by the main character, D-503, that is to be sent aboard a space shuttle to other planets in order to describe the greatness of OneState.
Hamlet Essay Research Paper Hamlet Leartes and
Hamlet Essay, Research Paper Hamlet, Leartes and Fortinbras all had some huge issues to work out in their lives. The way they worked out these problems is how we see the action behind the men and are able to recognize the traits that influenced all characters in the play, not just the ones discussed here. All three of these men avenge in very different ways.
Surviving Treblinka Essay Research Paper Surviving Treblinka
Surviving Treblinka Essay, Research Paper Surviving Treblinka The book, Surviving Treblinka, describes a miraculous story of one man s struggle to remain alive through each coming day and his escape from Germany s killing machine. Samuel Willenberg is one of a very small group of people, who have lived to tell about their horrific experiences in the concentration camps, but what made these people so different from all the others who never saw liberty again? Perhaps some individuals survived the Holocaust while others didn t because they received help from old acquaintances, had a very strong will to live and were in a close group of helpful friends during their imprisonment.
Notre Dame Essay Research Paper Notre Dame
Notre Dame Essay, Research Paper Notre Dame Notre Dame is a cathedral. The word cathedral comes from the Latin word cathedra, which is the name that was given to the throne was called where the
Untitled Essay Research Paper here ya go
Untitled Essay, Research Paper here ya go…have fun History Compare and Contrast the writings of Confucius, Hammurabi, and the book of the dead Three of the most famous writings from ancient civilizations are the writings of Confucius, Hammurabi’s code of laws, and Egypt’s Book of the Dead. At first, they seem very different, they’re from different times, regions, and religions, but they all offer a peek into what values ancient people considered important.
Gentle Ben Essay Research Paper A brown
Gentle Ben Essay, Research Paper A brown bear is the largest most dangerous big-game animal in North America. Even so ,Mark Anderson?s only friend is Ben, the
OnLine Recruitment Essay Research Paper Online recruiting
On-Line Recruitment Essay, Research Paper On-line recruiting is the process of attracting and hiring applicants for positions within an organization through use of the internet. In this paper I will assess an on-line recruitment service, identify the advantages and disadvantages of this vehicle as a recruiting technique for an organization, evaluate the pros and cons of dealing with virtual resumes, and develop criteria an organization can use for selecting an on-line recruiting service.
Birth Control
–Abstinence Essay, Research Paper Reminiscing about my high school days I can remember the pressure there was to have sex. Within the male high school community, having sex was a “right of passage”. As we all know this attitude was very wrong. There are many issues that affect young people these days. One of these one in three sexually active people will have contracted an STD.
Steriods 2 Essay Research Paper Are steroids
Steriods 2 Essay, Research Paper Are steroids a drug? Yes, they are considered drugs and some types are illegal. These types of steroids are very controversial because they help body builders to bulk up fast and they make the body builder gain weight and loose fat in a short period of time. But on the other hand steroids also destroy the body.
Eiffel Tower Essay Research Paper My report
Eiffel Tower Essay, Research Paper My report is on the Eiffel Tower. The Eiffel was built in 1889, for the celebration of the centennial of The French Revolution. Which was in 1789. The Eiffel Tower was named for the builder, Gustave Alexandre Eiffel.u7
The Code Of Hammurabi Essay Research Paper
The Code of Hammurabi Of the many law codes surviving from the ancient Middle East, perhaps the most famous is the Code of Hammurabi, sixth King of the Amorite Dynasty of Old Babylon. Today, the code, engraved in stone takes on a unique form as a piece of art. However, decoded it is clear that this stone was obeyed and served as a sort of political propaganda.
Titanic Outlinepaper
&bibliography Essay, Research Paper Outline In retrospect, blame for the sinking of the Titanic can be placed on the inferior materials used by the ship builder, the misled motivation of Captain Smith and the White Star Line, and the poor emergency provisions and procedures.
The Enlightenment Of The Buddha Essay Research
Paper The Enlightenment Of The Buddha In history, it has often been a single year, a single month, a single day, or even a singlenight, that has changed and shaped the lives of millions of people. The night when SiddarthaGautama was enlightened and became The Buddha was one of these history-changing times.
Master Builder Freudian Symbols Essay Research Paper
Freudian Symbols in The Master Builder The Master Builder, by Henrik Ibsen, is a play about individuality, morality, and self. But beneath those very ambiguous descriptions lies a play with symbols that clearly