Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Compile all files into a .lib

Part of StandardLibraryCategory

Description

This code will create a batch file that will compile files in the current directory into a .lib (designed for Windows).

With a little work, it might run on Linux, but I don't currently have a Linux machine set up for developing in D.

Example

import std.file : write, listdir, getcwd, DirEntry;
import std.path : getBaseName, getDirName, curdir;
import std.regexp : RegExp;
import std.stdio : writefln;
import std.stream : File;
import std.string : replace, rfind;


char[] bufLib;
char[] relPath;
char[] includePath;
char[] DirBase;

void main()
{   
    /* Recursively adds each of the files in the current directory to a batch 
    file as a compile command and creates a .lib. */

    char[] libName;
    
    /* TODO: command line argument to allow adjusting this. */
    char[] curPath = getcwd;

    /* TODO: command line argument to allow adjusting this. */
    DirBase = curPath ~ "\\";
        
    /* TODO: command line argument to allow adjusting this. */
    includePath = "-I.."; 
    
    int i = rfind(curPath, "\\");
    if(i>-1)
        libName = curPath[i + 1 .. curPath.length];
    else
        libName = "mylib";

    bufLib = "lib -c " ~ libName ~ ".lib";
    relPath = DirBase;
    char[] bufCompile = listdirfn(relPath);

    bufLib ~= \r\n;
    writefln("%s", bufCompile ~ bufLib);

    File f = new File();
    with(f)
    {
        f.create("makelib.bat");
        f.writeString(bufCompile ~ bufLib ~ "pause\r\nerase *.obj\r\n");
        f.close();    
    }
}



char[] listdirfn(char[] pathname)
{
    char[] outputData;
    auto r = new RegExp(r"\.d$");
    bool callback(DirEntry* de)
    {
        if (de.isdir)
        {
            listdir(de.name, & callback);
        }
        else
        {
            if(r.test(de.name))
            {
                /* Make the path relative */
                relPath = replace(relPath, getDirName(de.name), "");
                outputData ~= "dmd -c " ~ relPath ~ getBaseName(de.name) ~ " " ~ includePath ~ \r\n;

    	        /* Change the extention form ".d" to ".obj" and add to the lib command. */
    		    bufLib ~= " " ~ replace(getBaseName(de.name), ".d", ".obj");
            }
        }
        return true;
    }
    listdir(pathname, & callback);
    return outputData.dup;
}

Sample Batch File

@echo off
dmd CompileAllFilesIntoLibExample.d
CompileAllFilesIntoLibExample.exe
pause

Testing

Tested with Digital Mars D Compiler v0.177 on Windows 2000.