How do write a makefile for C#?

Viewed 13503

I have a simple C# program that needs to be run from the command line in Linux through mono. Here's what I have for my makefile so far. It's based off of a C++ makefile I found for another program. I tried modifying it to work with my C# program but it says certain source files could not be found.

.PHONY : build view clean

build : test
@# do nothing

test : test.o
gmcs test test.o

test.o : test.cs
gmcs test.cs

view :
@\less test.cs

clean :
-\rm *.exe
-\rm test

I've never worked with makefiles before so I don't really know what I'm doing wrong. There's only one file in my entire project and that's just test.cs. The final goal of this is to be able to run the program by typing in the command line:

./test

And it should clean up the .exe files generated too.

3 Answers

In order to answer the question, I will explain more about makefiles:
when you have a statement like that:

test: test.o
    gmcs test test.o

it means: in order to build target test, you will need target test.o and to run the command gmcs test test.o.

when you type in the command line make target it will try to build target by the rules you wrote in the makefile. So, in our case, when you execute make test the program will try to build test, see it needs to build test.o before, find this rule:

test.o: test.cs
    gmcs test.cs

find the file test.cs, run gmcs test.cs, then go back to the previous target, and run gmcs test test.o now, you don't have test nor test.o in your directory, so the command reports an error.

What got you confused (and i could just guess about this) is the c++ make file. In c++ you first create object files (.o in linux, .obj in windows), then link them together. I'm not sure, but the command in the c++ makefile you have for a .o target was with the -c flag - a flag that tells gcc to just compile. In your case the program was completely compiled after the first command.

So - the makefile you are looking for is the following:

PHONY : build view clean

build : test
@# do nothing

test: test.cs
    gmcs test.cs -out:test

view :
@\less test.cs

clean :
-\rm *.exe
-\rm test

that will create a file named test, and you could run it with mono test. if you want to omit the mono you can create a script file:

#! /bin/bash

mono test 

don't forget to change the permissions to allow you to execute it!

Related