Skip to content

Draft: Add import directive for packages

Akarin requested to merge akarin123/vala:import into master

This draft is a simple attempt (sorry if primitive) to add a keyword import to allow importing packages in Vala source files. The aim is to address the issue #1154.

The syntax is

import extern "external_pkg_name";
import "internal_pkg_name";

For example, with this draft, we can import an external package like this

// hellogtk.vala
import extern "gtk+-3.0";
using Gtk;

int main (string[] args) {
	Gtk.init (ref args);

	var window = new Window ();
	window.title = "Hello, World!";
	window.border_width = 10;
	window.window_position = WindowPosition.CENTER;
	window.set_default_size (350, 70);
	window.destroy.connect (Gtk.main_quit);

	var label = new Label ("Hello, World!");

	window.add (label);
	window.show_all ();

	Gtk.main ();
	return 0;
}

And compile it with a neat command

valac hellogtk.vala

The import extern will do the same thing as adding a --pkg gtk+-3.0 flag to valac.

On the other hand, in this draft, the keyword import without extern will load an "internal package". For example, if we have a directory src with the file main.vala and a subdirectory mymath

  • main.vala
  • mymath
    • mymath.a
    • mymath.vapi
    • mymath.h

and with this code in main.vala

// main.vala
import "mymath";
using MyMath;

public int main() {
    print("2 + 3 is %d\n", sum(2, 3));
    print("8 squared is %d\n", square(8));    

    return 0;
}

The mymath package is compiled from mymath.vala

// mymath.vala
namespace MyMath {
    public int sum(int a, int b) {
        return(a + b);
    }

    public int square(int a) {
        return(a * a);
    }
}

with the commands

valac mymath.vala -c --library=mymath -H mymath.h
ar -rcs mymath.a mymath.vala.o

The file main.vala then can be compiled with a neat command

valac main.vala

And it will utilize the static library mymath.a in the subdirectory mymath.

Thank you for consideration and suggestions!

Edited by Akarin

Merge request reports