Start and end code

Content:

This is inspired a LinkedIn post I saw, but that post itself was not so interesting.

This is about how a library can get code executed at start and end of program run. This is not standard but compiler/platform specific.

First C. GCC has an extension for this that is also supported by clang, so pretty widely supported (but not supported by traditional MSVC++).

C:\Work\C>type p.c
#include <stdio.h>

void s1();
void s2();

int main()
{
    printf("start\n");
    s1();
    s2();
    printf("finish\n");
    return 0;
}

C:\Work\C>type s1.c
#include <stdio.h>

void prt(const char *msg); // no guarantee that C RTL IO will work in init and done

__attribute__((constructor))
void s1_init()
{
    prt("s1 init\n");
}

__attribute__((destructor))
void s1_done()
{
    prt("s1 done\n");
}

void s1()
{
    printf("s1\n");
}
C:\Work\C>type s2.c
#include <stdio.h>

void prt(const char *msg); // no guarantee that C RTL IO will work in init and done

__attribute__((constructor))
void s2_init()
{
    prt("s2 init\n");
}

__attribute__((destructor))
void s2_done()
{
    prt("s2 done\n");
}

void s2()
{
    printf("s2\n");
}
C:\Work\C>type util.c
#include <string.h>

#include <windows.h>

void prt(const char *msg)
{
    DWORD actual;
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), msg, strlen(msg), &actual, NULL);
}

C:\Work\C>del p.exe

C:\Work\C>gcc p.c s1.c s2.c util.c -o p.exe

C:\Work\C>p
s2 init
s1 init
start
s1
s2
finish
s1 done
s2 done

C:\Work\C>del p.exe

C:\Work\C>clang-cl p.c s1.c s2.c util.c -o p.exe

C:\Work\C>p
s1 init
s2 init
start
s1
s2
finish
s1 done
s2 done

Then Pascal. VMS Pascal has supported this since the mid 1980's!

$ type p.pas
program p(input,output);

[external]
procedure s1; external;

[external]
procedure s2; external;

begin
   writeln('start');
   s1;
   s2;
   writeln('finish');
end.
$ type s1.pas
module s1(input, output);

(* no guarantee that Pascal IO will work in init and done *)
[external]
procedure prt(msg : packed array [l..h:integer] of char); external;

procedure s1_init;

begin
   prt('s1 init');
end;

procedure s1_done;

begin
   prt('s1 done');
end;

[global]
procedure s1;

begin
   writeln('s1');
end;

to begin do s1_init;
to end do s1_done;

end.
$ type s2.pas
module s2(input, output);

(* no guarantee that Pascal IO will work in init and done *)
[external]
procedure prt(msg : packed array [l..h:integer] of char); external;

procedure s2_init;

begin
   prt('s2 init');
end;

procedure s2_done;

begin
   prt('s2 done');
end;

[global]
procedure s2;

begin
   writeln('s2');
end;

to begin do s2_init;
to end do s2_done;

end.
$ type util.pas
[inherit('sys$library:pascal$lib_routines')]
module util;

[global]
procedure prt(msg : packed array [l..h:integer] of char);

begin
   lib$put_output(msg);
end;

end.
$ pas p
$ pas s1
$ pas s2
$ pas util
$ link p + s1 + s2 + util
$ run p
s1 init
s2 init
start
s1
s2
finish
s2 done
s1 done

Comments: