การใช้ Precompiled Headers ใน Visual C++

29. December 2008

หลังจากทรมานจนทนไม่ไหวกับการ Build ที่ช้ามากจนแทบทนไม่ได้ของ Visual C++ ทำให้ต้องไปหาวิธีเพิ่มความเร็วมาใช้ หนึ่งในนั้นคือการใช้ Precompiled Headers ของตัว Visual C++ เอง ทำให้ build กินเวลาน้อยลงมากอย่างไม่น่าเชื่อ

เริ่มจากต้องไปตั้งใน Project Property -> Configuration -> C/C++ -> Precompiled Headers ให้เป็น Use Precompiled Headers (/Yu) เสียก่อน

หลังจากนั้นสร้างไฟล์ stdafx.h กับ stdafx.cpp ขึ้นมา (หรือ copy มาจาก project ที่ทำไว้แล้วก็ได้) ข้างในมันจะคล้ายๆแบบนี้

stdafx.h

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

#include <Ogre.h>
#include <OIS/OIS.h>
#include <OgreFont.h>
#include <OgreFontManager.h>
#include <OIS/OIS.h>
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <stdio.h>
#include "bass.h"

stdafx.cpp

// stdafx.cpp : source file that includes just the standard includes
// TestPrecompiledHeaders.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

ในไฟล์ stdafx.h เราจะใส่ library ที่เราต้องการทำ precompiled headers ลงไป

ยังไม่จบ หลังจากนั้นเลือกเฉพาะไฟล์ sfdafx.cpp เท่านั้น  (ย้ำว่าเลือก .cpp ไม่ใช่ .h) ดู Property -> Configuration -> C/C++ -> Create Precompiled Headers (/Yc)

เสร็จแล้วในไฟล์ source code และ header อื่นๆนอกจาก 2 file ข้างบนที่ต้องการใช้ precompiled header ก็ใส่ #include "stdafx.h" เข้าไปแทน

เสร็จสมบูรณ์

ความบัดซบของวิธีนี้ก็คือว่า เนื่องจากมันเป็น Specific Feature ของ Visual C++ ดังนั้นถ้าจะพอร์ตไปแพลตฟอร์มอื่น ก็คงต้องเสียเวลาแก้กันหน่อย

Native , , ,

Comments

กร
กร
1/3/2009 1:05:41 AM #
อ่านไม่รู้เรื่อง
Comments are closed