0

I don't understand how to work with F# header files.

I have two test files:

Foo.fs:

module Foo
let add a b = a + b

Program.fs:

open Foo
printfn "%d" (add 8 2)

In the file Program.fs, Visual Studio tells me:

Files located in libraries or applications containing multiple files must start with a namespace or module declaration. Only the last source file of an application can omit such a statement.

However, I did the right thing: start my Foo.fs file with a module declaration. If I declare a namespace or module to Program.fs, the error persists. So I don't have access to the add function.

How do I import this file?

Foxy
  • 980
  • 8
  • 17
  • 2
    Are you sure that `Foo.fs` is listed before `Program.fs` in the project? – Fyodor Soikin Oct 07 '18 at 18:43
  • @FyodorSoikin: No, he's not. But now that you mention it, by moving `Foo.fs` above `Program.fs`, it works. I didn't know the problem came from Visual Studio. Can you explain to me why that's the way it works? – Foxy Oct 07 '18 at 19:45
  • 2
    @Foxy - In F#, you must list the files in your project in "dependency order", that is, if B.fs uses code from A.fs, then A.fs must be listed first and B.fs must be second. (Just like how, within a source file, if function Bar uses code from function Foo then you must declare Foo first and Bar second). Since your `Program.fs` uses code from `Foo.fs`, you must list `Foo.fs` first in the project file and `Program.fs` second. Also, [circular dependencies within files are not allowed](https://fsharpforfunandprofit.com/posts/cyclic-dependencies/). – rmunn Oct 07 '18 at 20:33
  • Thank you, this answers my questions and my problem is solved. – Foxy Oct 07 '18 at 20:36
  • 1
    @Foxy - By the way, you mention "header files" in your question, but F# doesn't have header files like C does. ([Neither does C#](https://stackoverflow.com/questions/11814771/why-doesnt-c-sharp-have-header-files-will-the-namespace-take-care-of-everythin?rq=1).) Rather, the compiler keeps track of all names in a given namespace and where they're defined, and knows how to find any function you refer to without your needing to explicitly point it at a specific file. This avoids the problem, common in C and C++, of multiply-included header files. – rmunn Oct 09 '18 at 13:09

0 Answers0