11
votes

I am a complete beginner with Ocaml programming and I am having trouble linking a module into my program. Actually I am doing some regular expression checking and I have written a function that basically tokenizes a string based on a separator string using the Str module . So i use the functions defined in the library like this:

Str.regexp_string /*and so on*/

However, when I try to compile the ml file, I get an error suggesting that I have an undefined global Str . We use List functions by typing in List.length and so on just like I did for Str without having to explicitly include the specific module. I tried

open Str;;
include Str;; /*None of these work and I still get the same error*/

However if in the toplevel I use

load "str.cma" /*Then the program works without problems*/

I want to include the module in the ml file because I have to in the end link 3 cmo's to get the final executable(which is not run in the toplevel). I know this is a really basic question but I am having trouble solving it. Thanks in advance.

4

4 Answers

13
votes

You don't need to add anything in your file foo.ml. You do need to tell the compiler where to find the Str module when compiling foo.ml . To do so, add it to the command line used to compile foo.ml:

ocamlc str.cma foo.ml

or

ocamlopt str.cmxa foo.ml

List and other modules from the standard library are accessible by default, so you don't need to tell the compiler about those often used modules.

0
votes

I think you need to use '-cclib ' compiler directive. The module name shouldn't include the file ending like .cma. Below is what I did when trying to use the unix and threads modules. I think you need to use some combination of the 'custom' and 'cclib' compiler directives.

ocamlc -custom unix.cma threa.ml -cclib -lunix

Look at chapter 7 of this book for help: http://caml.inria.fr/pub/docs/oreilly-book/html/book-ora063.html

And look at coverage of compiler directives here: http://caml.inria.fr/pub/docs/manual-ocaml-4.00/manual022.html#c:camlc

0
votes
ocamlc calc.ml str.cma -o calc
File "calc.ml", line 1:
Error: Error while linking calc.cmo:
Reference to undefined global `Str'

Code is very simple, to cut down scruff.

let split_into_words s = 
    Str.split ( Str.regexp "[ \n\t]+") s ;;

let _ = 
    split_into_words "abc def ghi" ;;

On ocaml 4.0.2. Obviously, there is a problem here, but I am too much of a beginner to understand what it is. From toplevel it seems work fine with #load "str.cma", so there is something here we don't understand. Anyone know what it is?

0
votes

Just add str to the libraries field of your dune file.