Is “implicitly imported” always a bad thing in Delphi packages?

天大地大妈咪最大 提交于 2019-11-29 03:07:45

Here's the issue:

You can only have one copy of a unit in your program. If you try to load the same unit twice via packages, it will raise an exception and the package won't load the second time. The way to avoid this is to structure your packages so that no unit is used in more than one of them.

The code to every unit you compile has to be in the package. The compiler will start with all the units you declare in the contains section, but any other units used by those units also has to be compiled in so it will be reachable, unless those units are contained in another package which is listed under requires. These extras are the "implicitly imported" units. Trouble is, they're imported implicitly, not explicitly stated in the contains section where they'll conveniently show up in the Project Manager off to the right. This means that you might not notice that your unit is in a package, and end up putting it in another one. Then when you try to run your program and load the packages, things break. That's why the compiler warns you about it.

It's a warning, and not an error, for a reason. As long as you understand how the system works, it's technically safe to use implicit imports. Just remember that those units are ending up in the package whether you declare them or not. But then again, since they're ending up there whether you declare them or not, it's probably simpler just to officially add them and save yourself the hassle.

Cobus Kruger

+1 for Mason's answer. The place where implicitly-imported units become a problem is on a large project where it becomes exponentially more difficult to keep track of units that are linked in from whereever.

I find the best way by far is to have a folder per package, and that folder contains all the files for the package. If I see an "implicit import" warning, I either add the required package, or add the unit to the package. So all units are specified in the package that contains them and they are all in the same folder. I never add folders to the Search Path, because every project knows about all its files directly.

The structure is really not terribly difficult to maintain and it protects you from problems where different units contain different versions of a file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!