Changing the order of compilation in an F# project

If you start a new F# project in Visual Studio then the first source file you’ll get is Program.fs with a main function. Then say you add another source file called Domains.fs with the following namespace and type:


type Book = {
    title: string;
    author: string
with member this.takesLongTimeToRead = this.numberOfPages > 500

The source file will at first land under Program.fs in the class hierarchy in Visual Studio:

New F# source file in the bottom of the file hierarchy

You then might want to use this Book type in the main function as follows:

namespace com.mycompany.entry

open System

module Main =    
    let main args =    
        let myBook = {title = "F# for beginners"; numberOfPages = 600; author = "John Smith"}        
        let longTimeOrNot = myBook.takesLongTimeToRead
        printfn "Book title: %s, takes long to read: %b" myBook.title longTimeOrNot
        let keepConsoleWindowOpen = Console.ReadKey()

However this will result in multiple compilation errors and red squiggly lines:

The namespace or module ‘com’ is not defined
The record label ‘title’ is not defined FSharpProjectExamples

…and various others.

The reason is that in F# projects the source files are compiled from top to bottom. Since Domains.fs comes after Program.fs the necessary elements such as the namespace haven’t been picked up in Program.fs.

One solution is to reorder the files. Right-click Program.fs and select “Move Down” in the context menu so that it will be the last file in the file hierarchy. The red squiggly lines and compiler errors should disappear. If you still see an exception with the message…

A function labeled with the ‘EntryPointAttribute’ attribute must be the last declaration in the last file in the compilation sequence, and can only be used when compiling to a .exe.

…with the “main” function underlined then clean the solution and rebuild it in Visual Studio. That should solve the problem.

View all F# related articles here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: