Difference between revisions of "Using C libraries for a D program"

From D Wiki
Jump to: navigation, search
(binding file needs to be compiled)
(-o -> -of)
(7 intermediate revisions by one other user not shown)
Line 6: Line 6:
 
::'''./main.d'''
 
::'''./main.d'''
  
* a C ABI library file:  
+
* a C ABI shared library file:  
 
::'''/usr/local/lib/libbu.so'''
 
::'''/usr/local/lib/libbu.so'''
  
* a D language binding file to the C library API headers:
+
* a D language binding interface file to the C library API headers:
 
::'''/usr/local/include/bu.d'''
 
::'''/usr/local/include/bu.d'''
  
Line 23: Line 23:
 
BINDING = $(MODDIR)/bu.d
 
BINDING = $(MODDIR)/bu.d
  
all: test-bu
+
PROG = test-bu
  
test-bu: main.o bu.o
+
all: $(PROG)
         $(DMD) -o $@ main.o bu.o -L$(LIBDIR) -lbu
+
 
 +
$(PROG): main.o bu.o
 +
         $(DMD) -of$@ main.o bu.o -L$(LIBDIR) -lbu
 
   
 
   
 
%.o: %.d
 
%.o: %.d
         $(DMD) -c $< -o $@
+
         $(DMD) -c $< -of$@
  
bu.o: #(BINDING)
+
bu.o: $(BINDING)
         $(DMD) -c $< -o $@
+
         $(DMD) -c $< -of$@
  
 
clean:
 
clean:
         -rm *.o</pre>
+
         rm $(PROG) *.o</pre>
  
 
Then we can build '''test-bu''' by executing:
 
Then we can build '''test-bu''' by executing:
Line 41: Line 43:
 
<pre>$ make test-bu</pre>
 
<pre>$ make test-bu</pre>
  
The GNU Makefile can be made more general and efficient, but it should produce the desired binary program.
+
The GNU Makefile can be made more general and efficient, but it should produce the desired binary program
 +
 
 +
Note also that a fully D-supporting C library installation would probably have the D binding interface available as a pre-compiled *.o file.

Revision as of 22:35, 13 January 2018

WARNING: This crude recipe by an absolute D newbie has not yet been tested--corrections are welcome!

Assume one has the following, error-free files:

  • a D language source program:
./main.d
  • a C ABI shared library file:
/usr/local/lib/libbu.so
  • a D language binding interface file to the C library API headers:
/usr/local/include/bu.d

We first create a GNU Makefile to build program test-bu using those three files (note the leading spaces on lines following targets must be tabs in a real GNU Makefile):

$ cat Makefile
# use the dmd compiler
DMD = /usr/bin/dmd

LIBDIR = /usr/local/brlcad/lib
MODDIR = /usr/local/brlcad/include

BINDING = $(MODDIR)/bu.d

PROG = test-bu

all: $(PROG)

$(PROG): main.o bu.o
        $(DMD) -of$@ main.o bu.o -L$(LIBDIR) -lbu
 
%.o: %.d
        $(DMD) -c $< -of$@

bu.o: $(BINDING)
        $(DMD) -c $< -of$@

clean:
        rm $(PROG) *.o

Then we can build test-bu by executing:

$ make test-bu

The GNU Makefile can be made more general and efficient, but it should produce the desired binary program.

Note also that a fully D-supporting C library installation would probably have the D binding interface available as a pre-compiled *.o file.