Delphi dcp файл что это
Вы когда ни будь задумывались о том, что создает Дельфи в папке с исходниками проекта? Да и нужен ли весь этот абсолютно бесполезный, для рядового программиста, "мусор"? Пора призадуматься. В этой мини-статье я расскажу о назначении таких файлов.
Вступление прочитали, сразу к делу. По правде говоря, я опишу не только те файлы, которые создаются в папке с исходниками, но и некоторые другие, что, думаю, будет интересно всем. Буду описывать в алфавитном порядке. Итак, пристегнулись? Поехали!
.BPG - Borland Project Group: это разновидность файла сборки.
.BPL - Borland Package Library: этот файл есть ничто иное как обыкновенная (или нет?) DLL, которая включает в себя компоненты VCL. Что такое компоненты, я думаю, объяснять не стоит.
.CFG - Файл конфигурации: содержит параметры проекта, аналог файлов .DOF
.DCP - Delphi Component Package: грубо говоря, это исходники компонента. Скомпилированные компоненты содержатся в .BPL.
.DCU - Delphi Compiled Unit: наверное самый часто встречающийся тип файлов. Он содержит откомпилированный код юнита, с помощью него ускоряется компиляция.
.DDP - Delphi Diagram Portfolio: вы заглядывали на вкладку Diagramm в окне редактирования кода? Вот эти файлы содержат как раз эти схемы, которые можно создавать в том окне.
.DFM - Delphi Form File: здесь в двоичном виде хранится описание формы и компонентов, которая эта форма содержит
.~DF - Резервная копия файла формы: в большинстве случаев она бесполезна, зря засоряет винчестеры. Так что гнать в шею! (точнее отключить в настройках :)
.DOF - Delphi Options File: содержит (в текстовом виде) текущие параметры проекта.
.DPK - Delphi PacKage: исходник проекта пакета.
.DPR - Delphi PRoject: исходник проекта проекта, точнее файл с исходным текстом проекта вашей программы
.~DP - Резервная копия DPR: см. .~DF
.DSK - DeSKtop: файл с настройками рабочей среды Дельфи.
.DSM - Delphi Symbol Module: имеет сомнительную полезность.
.DCI - Delphi Code Templates: шаблоны кода дельфи. Помоему в комментариях не нуждается.
.DRO - Delphi Object Repository: репозитарий обьектов (Tools - Repositary).
.DMT - Delphi Menu Templates: шаблоны менюшек дельфи.
.DCT - Delphi component Temlates: шаблоны компонентов дельфи.
.OBJ - OBJect: обьектный файл, который применяется в C/C++. Он используется в том случае, если вы хотите скомпилировать программу с скомпилированным кодом (из OBJ файла) из C/C++
.PAS - PAScal: исходник модуля (юнита)
.~PA - Резервная копия PAScal: см. .~DF
.RES .RC - ResourCe: двоичный файл ресурсов программы, таких как картинки, иконки, формы и прочее.
.TODO - TODO: файл списка To-Do (сделать) списка. Обычно полезен в том случае, если программа разрабатывается коллективом программистов.
Если вам помог материал сайта кликните по оплаченной рекламе размещенной в центре
bpl я подключил, возникли новые компоненты. Но с ними проект не компилируется, просит некие dcu файлы.
← →Dilezzz ( 2003-09-03 23:39 ) [10]
Тут есть кто живой?
← →Dilezzz ( 2003-09-05 18:03 ) [11]
НУ ЧТО, ПРАВДА НИКТО НЕ ЗНАЕТ КАК УСТАНОВИТЬ КОМПОНЕНТ .
Зачем вместе с компонентом постовляется файл dcp .
← →panov ( 2003-09-05 18:30 ) [12]
Зачем вместе с компонентом постовляется файл dcp .
Можно просто F1 нажать на этом сочетании из 3-х букв.
A binary image containing a package header and the concatenation of all dcu (Windows) or dpu (Linux) files in the package. A single dcp file is created for each package. The base name for the dcp is the base name of the dpk source file.
← →Dilezzz ( 2003-09-05 19:24 ) [13]
НУ ! А как теперь установить компонент?! Компилятор на отсутствие dcu ругается, а они судя по всему все в этом dcp! Че делать?
← →Вася Пупкин ( 2003-09-05 19:33 ) [14]
головой подумать. и указать компилятору путь к этому самому dcp - глядишь, и поможет
← →Dilezzz ( 2003-09-06 00:46 ) [15]
как указать?
← →Dilezzz ( 2003-09-06 12:45 ) [16]
ау
← →Вася Пупкин ( 2003-09-06 12:54 ) [17]
1) Файлы пакетов
.dpk - Исходный файл пакета - создаетчся при запуске редактора пакетов.
.dcp - символьный файл пакета времени выполнения и разработки - скомпилированная версия пакета с символьной информацией о пакете и его модулях. Кроме того, в нем содержится заголовок с информацией, необходимой среде разработки
.dcu - скомпилированный модуль - скомпилированная версия модуля, содержащегося в пакете. Для каждого модуля, содержащегося в пакете, создается собственный dcu-файл
.bpl - пакет библиотеки времени выполнения и разработки - эквивалент библиотеки dll windows. Если это пакет времени выполнения, надо распространять его вместе с приложениями, которые его используют.
Если не распространяется исходный код пакета разработки, должен быть предоставлен соответствующий ему .dcp-файл
Вася Пупкин ( 2003-09-06 13:02 ) [18]
2)
Файл dcp можно поместить туда же, где лежит соответствующий файл bpl.
3)Вместе с пакетом разработки должны распространяться скомпилироыванные модули dcu. Путть поиска должен включать папку, где лежат эти dcu.
3) Если не поможет (2) и установка галки "build with runtime packages" - тогда уже не у нас спрашивай, где dcu-файлы.
4) пути можно указать в опциях проекта либо в Component->NewComponent ( это на вопрос - как указать)
5) Так вопросы не задают - никогда не получишь исчерпывающего ответа. Да и вообще имеешь шанс не получить ответ.
Здесь не экстрасенсы:
- откуда известно, что у тебя за компонент такой.
- Почему к нему нет readme-файла с инструкцией по установке,
-полный ли у тебя комплект (подозркеваю, что всё же не хватает файлов dcu)
circul ( 2003-09-06 23:46 ) [20]
АУ!
Так у тебя что-то получилось или нет?
← →Dilezzz ( 2003-09-07 15:31 ) [21]
Ничего у меня не получилось
>- Почему к нему нет readme-файла с инструкцией по установке,
не прилагался потому что.
>-полный ли у тебя комплект (подозркеваю, что всё же не хватает файлов dcu)
Packages are typically the preferred way to export items other than simple procedures and functions. Libraries should only be considered when interopability with other programming is a requirement.
The following topics describe packages and various issues involved in creating and compiling them.
- Package declarations and source files
- Naming packages
- The requires clause
- Avoiding circular package references
- Duplicate package references
- The contains clause
- Avoiding redundant source code uses
- Compiling packages
- Generated files
- Package-specific compiler directives
- Package-specific command-line compiler switches
Types of Packages [ ]
Delphi knows two different types of packages, runtime packages and designtime packages.
Runtime Packages [ ]
Runtime packages are meant to be distributed with applications, just like dlls are, to keep down the executable size and prevent distributing lots of duplicate code.
Contents
Avoiding redundant source code uses
A package cannot be listed in the contains clause of another package or the uses clause of a unit.
All units included directly in a package's contains clause, or indirectly in the uses clauses of those units, are bound into the package at compile time. The units contained (directly or indirectly) in a package cannot be contained in any other packages referenced in requires clause of that package.
A unit cannot be contained (directly or indirectly) in more than one package used by the same application.
Generated Files
The following table lists the files produced by the successful compilation of a package.
Compiled package files
A binary image containing a package header and the concatenation of all .dcu (Win32) files in the package. A single .dcp or .dcp file is created for each package. The base name for the file is the base name of the .dpk source file.
The runtime package. This file is a DLL on Win32 with special RAD Studio-specific features. The base name for the package is the base name of the dpk source file.
The requires clause
The requires clause lists other, external packages that are used by the current package. It functions like the uses clause in a unit file. An external package listed in the requires clause is automatically linked at compile time into any application that uses both the current package and one of the units contained in the external package.
If the unit files contained in a package make references to other packaged units, the other packages should be included in the first package's requires clause. If the other packages are omitted from the requires clause, the compiler loads the referenced units from their .dcu files.
Compiling and Installing [ ]
It's about time something gets added to the IDE, so let's compile and install the packages. First, select "Build" from the context menu of the runtime package and after that do the same with the designtime package.
The IDE will compile both and create 4 files:
MyPackage100.bpl The runtime package (.bpl = Borland Package Library). MyPackage.dcp The (.dcp = Delphi Compiled Package) .dcp file for the runtime package contains the headers of all units in that package so the compiler can easily access them without actually accessing the units themselves. DclMyPackage100.bpl The designtime package. DclMyPackage.dcp The .dcp file for the designtime package.
To add the new component to the Component Palette, we must install the designtime package into the IDE. That's easily done using its context menu: "Install". The IDE will now load the designtime package and tell you that a new component called "TMyButton" has been registered.
Switch to the Component Palette (Ctrl-Alt-P) to verify that, yes, there is a new group called "My Components" and that it contains (drum roll. ) TMyButton! Hmm, no, something is wrong. There is no such group and no such component! Has the IDE been lying?
If you look closer, you will see that there aren't any components at all. The reason for this is that the IDE is (trying to be) clever: You have not selected any form so you don't really need any components.
Let's just create a new VCL application to verify this theory: Select "New -> VCL Forms Application - Delphi for Win32" from the "File" menu. The IDE will ask you to save your changes to the packages (do it) and then create the project, automatically creating the first form for us. Now, look at the Component Palette again! (Drum roll. ) There we go: A group called "My Components" containing "TMyButton".
Package-Specific Compiler Directives
The following table lists package-specific compiler directives that can be inserted into source code.
Package-specific compiler directives
Prevents a package from being implicitly recompiled later. Use in .dpk files when compiling packages that provide low-level functionality, that change infrequently between builds, or whose source code will not be distributed.
Disables creation of imported data references. This directive increases memory-access efficiency, but prevents the unit where it occurs from referencing variables in other packages.
Packages unit weakly.
Prevents unit from being placed in a package.
Compiles the package for installation in the IDE. (Put in .dpk file.)
Compiles the package as runtime only. (Put in .dpk file.)
Including in source code prevents the unit file from being packaged. Including or may prevent a package from being used in the same application with other packages.
Other compiler directives may be included, if appropriate, in package source code.
Understanding Packages
A package is a specially compiled library used by applications, the IDE, or both. Packages allow you to rearrange where code resides without affecting the source code. This is sometimes referred to as application partitioning.
Runtime packages provide functionality when a user runs an application. Design-time packages are used to install components in the IDE and to create special property editors for custom components. A single package can function at both design time and runtime, and design-time packages frequently work by referencing runtime packages in their requires clauses.
On Win32, package files end with the .bpl (Borland package library) extension.
Ordinarily, packages are loaded statically when an applications starts. But you can use the LoadPackage and UnloadPackage routines (in the SysUtils unit) to load packages dynamically.
Note: When an application utilizes packages, the name of each packaged unit still must appear in the uses clause of any source file that references it.
Deployment [ ]
As said before, since we built with runtime packages, we must deploy them with the application. In our simple case it should be enough to include the packages rtl100, vcl100 and MyPackage100. To test this, you need a computer that does not have Delphi on it. Copy the packages and the executable to one directory and start it. If something is missing, the program loader will complain and tell you which other packages are needed.
Setting up a runtime package [ ]
Now that we have created a package, let's tell Delphi that it is a runtime package: Open the project options (either from the main Project menu or from the context menu of the Project Manager, shortcut: Alt+P, O). On the "Description" page do the following:
- Into the field called "Description" enter a short description of the package like "My first package".
- Under "Usage options" select "Runtime only"
- Under "Build control" select "Explicit rebuild"
- In the "Package name" group box, enter a LIB Suffix that corresponds to your Delphi version:
- Delphi 2006: "100"
- Delphi 2005: "90"
- etc; you get the picture (See Package Suffixes for a list of Delphi versions and the package suffixes they use)
Click OK to close that dialog.
So, what have we done?
- We have set a description for the package. This description will never really show up for a runtime package, but give one anyway just to get into the habit. It is more important for a designtime package.
- We set the package to be a runtime only package. This means that the IDE will tell you that it is a runtime package and refuse to install it. That's a good thing.
- We set the package to be built only explicitly. That's actually a matter of taste. I for one don't like the IDE trying to rebuild every bloody package if I only change one line in another package.
- We set the LIB Suffix to e.g. 100 which will make the package file always have a compiler version dependant suffix to help users to determine which package to use for their version of Dephi. This is not a requirement, but Borland does it for their own packages so why shouldn't we? If you look closely at the Project Manager, you will find that the new package is no longer called "Package1.bpl" but "Package1100.bpl". There's the suffix we just added.
Now it's time to save this package to an actually meaningful name. Select "Save Project As" in the File menu and call it e.g. "MyPackage.bdsproj". Look closely at the Project Manager and you will see that it is now called "MyPackage100.bpl".
If you open an explorer window and open the folder into which you just saved your package, you will find the following files:
Compile your new package, we will need that for the next step.
Compiling Packages
Packages are ordinarily compiled from the IDE using .dpk files generated by the Project Manager. You can also compile .dpk files directly from the command line. When you build a project that contains a package, the package is implicitly recompiled, if necessary.
Duplicate package references
The compiler ignores duplicate references in a package's requires clause. For programming clarity and readability, however, duplicate references should be removed.
Package Declarations and Source Files
Each package is declared in a separate source file, which should be saved with the .dpk extension to avoid confusion with other files containing Delphi code. A package source file does not contain type, data, procedure, or function declarations. Instead, it contains:
- a name for the package.
- a list of other packages required by the new package. These are packages to which the new package is linked.
- a list of unit files contained by, or bound into, the package when it is compiled. The package is essentially a wrapper for these source-code units, which provide the functionality of the compiled package.
A package declaration has the form:
where packageName is any valid identifier. The requiresClause and containsClause are both optional. For example, the following code declares the DATAX package:
The requires clause lists other, external packages used by the package being declared. It consists of the directive requires, followed by a comma-delimited list of package names, followed by a semicolon. If a package does not reference other packages, it does not need a requires clause.
The contains clause identifies the unit files to be compiled and bound into the package. It consists of the directive contains, followed by a comma-delimited list of unit names, followed by a semicolon. Any unit name may be followed by the reserved word in and the name of a source file, with or without a directory path, in single quotation marks; directory paths can be absolute or relative. For example:
Note: Thread-local variables (declared with threadvar) in a packaged unit cannot be accessed from clients that use the package.
Creating a package [ ]
Creating a new package is as simple as creating a new application. From the File menu select New -> Package - Delphi for Win32. In the Project Manager, you will now find a tree node called "package1.bpl" which has the sub nodes "Contains" and "Requires". If you expand the "Requires" node, you will find that Delphi has automatically added "rtl.dcp" to that.
Setting up a Design-time Package [ ]
As pointed out above, a designtime package is meant to be loaded into the Delphi IDE. You should always keep your designtime code separated from your runtime code, so it is best to always create two packages for your components from the start.
To create a designtime package you just create a new package as described above. The only difference is in the project options:
You can use the same description as for the runtime package, e.g. "My first package".
There is another difference to a runtime package: A designtime package must interact with the IDE and therefore needs to know about its internals. To make that possible, it needs the package "DesignIDE", which comes with any Delphi version. So we must add this package to the Requires section:
Right click on the "Requires" node of your new package and select "Add Reference". You get a dialog for entering or selecting the package. It is easier to just type in "DesignIDE" rather than using the file select dialog to find it, but just for the record: It is located in "c:\program files\borland\bds\4.0\lib" and called "designide.dcp".
Also, since we want to use this package to install the components that will be put into our runtime package, it must reference that package as well. So repeat the above to add "MyPackage" to the list of Required packages. Note that here you do not include the LIB suffix ("100"), but just the package name. When you press OK you will get an error message "File MyPackage.dcp not found.". The IDE does not know where to look for it, so this time we need the browse button. Normally the .dcp files the IDE generates are put into "\Borland Studio Projects\bpl".
Now save your new package into the same directory as the runtime package. You could give it any name you like, but the convention here is to use the runtime package's name with a "Dcl" prefix. I guess the D stands for designtime but I haven't got a clue what the prefix means. But Borland does it and pretty much any component vendor does, so why not follow that example and call it "DclMyPackage"?
(My guess is: DCL = Designtime Component Library --Dummzeuch 15:43, 1 July 2007 (UTC))
Package-Specific Command-Line Compiler Switches
The following package-specific switches are available for the command-line compiler.
Package-specific command-line compiler switches
Disables creation of imported data references. Using this switch increases memory-access efficiency, but prevents packages compiled with it from referencing variables in other packages.
Specifies the directory where the compiled package file .bpl will be placed.
Specifies the directory where the .dcp file will be placed.
-LUpackageName[;packageName2;. ]
Specifies additional runtime packages to use in an application. Used when compiling a project.
Prevents a package from being implicitly recompiled later. Use when compiling packages that provide low-level functionality, that change infrequently between builds, or whose source code will not be distributed.
Using the -$G- switch may prevent a package from being used in the same application with other packages.Other command-line options may be used, if appropriate, when compiling packages.
Проект Delphi состоит из форм, модулей, установок параметров проекта, ресурсов и т.д. Вся эта информация размещается в файлах. Многие из этих файлов автоматически создаются Delphi, когда вы строите ваше приложение. Ресурсы, такие, как битовые матрицы, пиктограммы и т.д., находятся в файлах, которые вы получаете из других источников или создаете при помощи многочисленных инструментов и редакторов ресурсов, имеющихся в вашем распоряжении. Кроме того, компилятор также создает файлы. Давайте бегло познакомимся с некоторыми из этих файлов, так как знание того, какие файлы какую информацию содержат, не раз поможет вам в трудных ситуациях.
Когда вы проектируете ваше приложение, Delphi создает следующие файлы:Следующая группа файлов создаётся компилятором:
Это двоичный файл, содержащий заголовок пакета и список принадлежащих ему файлов
И, наконец, другие файлы Windows, которые могут использоваться Delphi:
Главной частью вашего приложения является файл проекта (.dpr), содержащий код на языке Object Pascal, с которого начинается выполнение вашей программы и который обеспечивает инициализацию других модулей. В большинстве случаев вы можете создать законченное приложение Delphi, так и не взглянув на этот файл. Он создается и модифицируется Delphi автоматически в процессе вашей разработки приложения. Имя, которое вы даете файлу проекта, когда сохраняете его, становится именем исполняемого файла.
Приведенный ниже код является примером того, как выглядит файл проекта в случае, если вы, начав новый проект, не изменяли в нем имен файлов и форм.
program Project1
uses
Forms,
Unit1 in 'unit1.pas' ;Этот код содержит всего два выполняемых оператора. Первый из них создает форму Form1, а второй запускает выполнение приложения.
Все изменения файла проекта при добавлении новых форм, изменении имен форм и т.п. поддерживаются Delphi автоматически. Если вам необходимо посмотреть исходный файл проекта, надо выполнить команду View | Project Source. Но обычно это вам не требуется.
Не следует без нужды изменять файл проекта. Это может привести к несогласованности используемых имен и к прочим неприятностям.
Информация о формах Delphi хранится в двух файлах. В файле с расширением .dfm хранится информация о внешнем виде формы, ее размерах, местоположении на экране и т.д. В текстовом файле с расширением .pas хранится код модуля, соответствующего данной форме. Имена обоих этих файлов одинаковы. Вы задаете это имя, когда в первый раз сохраняете ваш модуль.
В версиях Delphi, предшествующих Delphi 5, файл формы .dfm был двоичным. Для того чтобы посмотреть его в текстовом виде, надо было щелкнуть на форме правой кнопкой мыши и из всплывшего меню выбрать раздел View as Text. Тогда в окне Редактора Кода появлялся текстовый файл формы. При желании его можно было редактировать. Для возврата к графическому представлению формы надо было на тексте файла щелкнуть правой кнопкой мыши и выбрать команду View As Form.
Все эти возможности сохранены и более новых версиях. Но, начиная с Delphi 6, пользователю предоставляется возможность выбрать, в каком виде он предпочитает сохранять файл формы: текстовом или двоичном. Если вы щелкнете на форме правой кнопкой мыши, то увидите во всплывшем меню индикатор Text DFM. По умолчанию он включен и файлы форм хранятся в текстовом виде. Если выключить этот индикатор, то файлы форм будут храниться в двоичном виде. Вы можете создавать модули, не привязанные к конкретным формам. Например, в большом приложении полезно иметь модуль, содержащий константы, переменные, процедуры и функции, используемые в различных модулях. Наличие такого модуля позволяет сократить число взаимных ссылок различных модулей.
К тому же подобный модуль может использоваться в разных ваших проектах. Чтобы создать в вашем проекте новый модуль, не связанный с какой-либо формой, надо выполнить команду File | New | Other и в открывшемся окне New Items на странице New щелкнуть на пиктограмме Unit.
Теперь надо сказать несколько слов о выполняемом файле .ехе и о файлах пакетов. В Delphi можно разрабатывать прикладные программы двух видов — автономные выполняемые файлы .ехе и программы с поддержкой пакетов (packages) времени выполнения. В последнем случае размер выполняемого файла заметно сокращается, но зато вы должны поставлять пользователю не только выполняемый модуль, но и файлы поддерживающих его пакетов. В следующих уроках будут рассмотрены достоинства и недостатки использования пакетов времени выполнения. Не останавливаясь сейчас на этих вопросах, отметим, что во время отладки, пожалуй, всегда имеет смысл включать поддержку пакетов времени выполнения. Это существенно сократит размеры выполняемых файлов и сбережёт вам немало дискового пространства.
Для использования этой возможности выполните команду Project | Options. В открывшемся окне опций проекта выберите страницу Packages и на странице Packages включите индикатор Built with runtime packages. Одновременно полезно включить в том же окне индикатор Default, что обеспечит статус этой установки как установки по умолчанию для всех ваших будущих проектов.
Только не забудьте при заключительной компиляции законченного проекта выключить опцию поддержки пакетов, если вы намерены передавать пользователях автономный выполняемый модуль.
After you have created a few components you probably want to put them into their own package rather than having them all in the dclusr package.
Here are a few hints about packages:
Saving the Project Group [ ]
Since we are at it, let's save the project group as well. From its context menu select "Save Project Group" and save it to the same directory as your packages. You can call it whatever you like, maybe "MyPackageGroup"?
Now you can open both, the runtime and the designtime package, by just opening the project group.
Adding a component - the right way [ ]
If you haven't created a package before, but have created your own component(s), you have probably added them to the default dclusr package. If you haven't created any component, yet, here is how to do it:
The contains clause
The contains clause identifies the unit files to be bound into the package. Do not include file-name extensions in the contains clause.
Conclusion [ ]
You do not need any designtime code, so the DclMyPackage package is not deployed. Since it contains references to the DesignIDE package, which you are not allowed to distribute, that would violate the licence.
This is the real reason why you should from the beginning divide your packages and units into designtime and runtime code. If you try that at the end, you will probably find it much more difficult to do.
Avoiding circular package references
Packages cannot contain circular references in their requires clauses. This means that
- A package cannot reference itself in its own requires clause.
- A chain of references must terminate without rereferencing any package in the chain. If package A requires package B, then package B cannot require package A; if package A requires package B and package B requires package C, then package C cannot require package A.
Naming packages
A compiled package involves several generated files. For example, the source file for the package called DATAX is DATAX.DPK , from which the compiler generates an executable and a binary image called
DATAX.BPL and DATAX.DCP
DATAX is used to refer to the package in the requires clauses of other packages, or when using the package in an application. Package names must be unique within a project.
An Example Application [ ]
So now we have got the packages and just created a new application. Let's use that to demonstrate how to deploy an application with our runtime packages.
Add a TMyButton component to the form. Add an OnClick event with the following code
(Of course in a real life application you would give Form1 and MyButton1 some meaningful names.)
Designtime Packages [ ]
Designtime packages are meant to be loaded by the Delphi IDE. They contain code to register components with the component palette, also they usually contain the component's icon since that also is only needed for the IDE.
Splitting runtime and designtime code [ ]
So we must split the code from that unit. Since we added the unit to the runtime package, let's keep the runtime code there.
Now, make the designtime package the current one by double clicking on it in the Project Manager. Select "Add New -> Unit" from its context menu, and save that unit as "de.dummzeuch.MyPackageRegister" into the folder with your packages.
Move the designtime code to the new unit:
- the declaration of the procedure "Register"
- the implementation of the procedure "Register"
The IDE will now flag the "RegisterComponents" call as an error. That's because the unit is missing something from its uses clause. Do you know where it is declared? Let's have a look at the original unit again (I was about to show you the power of Refactoring here, but the IDE couldn't find the declaration :-( ). It uses the units SysUtils, Classes, Controls and StdCtrls. Guess? No, it's not SysUtils, it's Classes, where it is declared. So we add it to the uses list of our new unit.
The IDE is still complaining, now about TMyButton, so we add de.dummzeuch.MyButton as well, to make it shut up.
"What?", you probably think, "we add the runtime unit to the uses clause of the designtime unit? That must be wrong!" OK, you probably didn't think that, but let's just assume you did, so I can explain: Earlier on, we have added the runtime package to the Requires list of the designtime package. This means that any unit from the runtime package can be used in the designtime package without including it there as well. And since we want to register the new component, we must be able to reference it.
. with Runtime Packages [ ]
Save it, compile it, run it. Stop! No, it doesn't compile, why is that?
Even though we have added the packages to the IDE we have not added the MyPackage directory to the search path so the compiler cannot find the unit "de.dummzeuch.MyButton".
Now is the time for a decision: Do we want to compile using runtime packages or not? If we use runtime packages, everything will work, but we must deploy the executable with the packages otherwise it won't even start. If we do not use runtime packages, we will have to add to the search path.
I'll decide for you: You want runtime packages. So open the Project Options, switch to the "Packages" page and set the checkmark for "Build with runtime packages". Have a look at the packages listed below that (click the ". " button). It should contain "MyPackage", probably right at the end. Close both dialogs with OK.
Save it, compile it, run it. Yes, it works now, but why? If you build with runtime packages the compiler will use the .dcp files of all included packages to search for missing units. Our MyPackage.dcp contains de.dummzeuch.MyButton, so now it can compile.
What's wrong? [ ]
Look at the unit that the IDE has just created. It contains two things:
- A new class declaration "TMyButton", which derives from "TButton"
- A procedure "Register", which calls "RegisterComponents" to register it in the IDE.
So what's wrong here? Yes? The unit contains runtime code (the class declaration) and designtime code (the register procedure) in one unit.
This is not the correct way to write packages, as even Borland says somewhere in the online help (look it up, it's there!).
Adding a component using the wizard [ ]
First, make the runtime package the current project by double clicking on it in the Project Manager.
From the context menu select "Add New -> Other" to open the "New Items" dialog. Since you are adding to a package, the possibilities are limited. Select the "Delphi Files" category and double click the "Component" icon.
You now get yet another dialog, the "New VCL Component" wizard. We don't want to make it difficult, so let's just create a new component based on TButton. Select it from the list (it supports incremental search, btw.) and click "Next".
On the next page, give your new button a class name. It must be unique within the whole IDE, including any 3rd party components. Use your imagination (I haven't got much of that, so I'll call it "TMyButton" for now). Select a palette page, or rather enter a new name like "MyComponents".
The Unit name also must be unique within all run- and designtime packages loaded by the IDE. From Delphi 7 on, a unit name can contain dots, so let's follow the Java tradition and use your domain name as a prefix, to make sure we don't get any clashes. (You haven't got any domain? Right, then let's just assume one like http://www.dummzeuch.de [That's my own domain, so please don't distribute any packages with that prefix!], so the unit would be called "de.dummzeuch.MyButton.pas".)
Save it to the same directory as your packages. Click "Finish" to close the wizard.
Select "Save All" from the "File" menu to save your work.
Читайте также: