Can I create a package with friendly modules
Tejas
notrealemail at gmail.com
Mon Jun 13 06:05:03 UTC 2022
On Sunday, 12 June 2022 at 05:05:46 UTC, forkit wrote:
> Is it possible to create a package.d, consisting of (for
> example), two modules, where each module can access private
> declarations within each other.
>
> In essence, declaring 'a module level friendship', or a kind of
> 'extended module' if you want.
>
> I might still want to add another module to the package, that
> is NOT part of that friendship between those other two modules,
> but is otherwise related to the solution.
You can use `package(qualifiedIdentifier)` to satisfy this to a
greater extent
Directory structure:
```sh
src
|
|--- main_file.d
|
|---parent
|
|--- driver.d
|
|--- package.d
|
|--- thing
|
|--- package.d
|
|--- first.d
|
|--- second.d
|
|--- third.d
```
Code :
`src/main_file.d`:
```d
import parent;
void main()
{
func();
}
```
`src/parent/package.d`:
```d
module parent;
public import
driver;
```
`src/parent/driver.d`:
```d
module parent.driver;
import thing;
void func()
{
S s; // from third.d
auto t = first.a; // from second.d
auto l = second.dbl; // from first.d
}
```
`src/parent/thing/package.d`:
```d
module parent.thing;
public import
first,
second,
third;
```
`src/parent/thing/first.d`:
```d
module thing.first;
import second;
static this()
{
a = second.g; // can also access symbols within neighbouring
modules
}
package(parent):
int a;
int b;
string c;
```
`src/parent/thing/second.d`:
```d
module thing.second;
package(parent):
int g;
char p;
double dbl;
```
`src/parent/thing/third.d`:
```d
module thing.third;
package(parent):
struct S
{
int a;
char c;
string s;
}
private S private_struct; // can't access via parent package,
since marked private
```
You run it via:
`dmd -i -I=./parent -I=./parent/thing main_file.d`
(I'm pretty sure it'll look far prettier using `dub`)
Here, all the symbols that are within package `thing` are visible
to package `parent` as well, but not visible to any other
package/module
More information about the Digitalmars-d-learn
mailing list