Using Mono to avoid depending on the .NET Framework on Windows

At GDC I remember seeing Brendon Chung’s talk about Atom Zombie Smasher, where he mentioned how it runs on Mono, even on Windows. Besides making the game’s behavior more consistent between Windows, Linux and Mac, it also allowed him to remove the need to install the .NET framework before running the game, since he can just bundle Mono with his game.

This is attractive to me for a few reasons:

  • It means all Windows players could play my game just by unzipping it — no separate step to install the .NET framework, no need for an installer to do it for them
  • It means I don’t have to target .NET 2.0 to try to keep Vista/Win7 users from needing to install the .NET framework — I can use nice 4.0 features
  • If I can get my game running on Mono, I can probably run on Linux and Mac as well

So I started looking into Mono. It turns out they have a utility called mkbundle that bundles your app, and all of the assemblies it depends upon, into a single executable, and the only thing it needs to run is a mono DLL you can distribute along with it. The .NET assemblies provided by Mono are MIT/X11 licensed, but the runtime is LGPL, so while you can embed Mono’s System.dll into your executable, you have to either dynamically link to the runtime DLL or otherwise provide your program to users in such a way that they could use a different Mono runtime if they wanted.

Unfortunately mkbundle is kind of broken on Windows right now, a lot of which is due to Cygwin drift since the tool was written. Luckily, it’s not so broken that you can’t fix it yourself. I mostly followed this StackOverflow answer — but there are a few changes I made to make it a lot simpler!

The procedure

  1. First, make sure your app works under Mono on Windows. If it doesn’t, none of this will be any use to you.
  2. Install Mono for Windows from here. Click the Windows button in the top row (the stable release) and choose “Mono for Windows, Gtk#, and XSP.” I used version 2.10.8, I can’t guarantee that anything else will work exactly as described. You can install to the normal directory.
  3. Install Cygwin (UNIX-like environment for Windows.) Make sure you have selected the packages gcc-mingw, mingw-zlib1, mingw-zlib-devel, and pkg-config.
  4. Launch a Cygwin Terminal using the shortcut created by the Cygwin installer.
  5. Navigate to the directory your game assemblies are (e.g. your bin/Release folder.) Note that in cygwin, a path like C:\some\path is expressed as /cygdrive/c/some/path — note the slash direction and the way drive letters work! Backslashes are escape characters in bash so if you just type \cygdrive\c\Foo it thinks you meant cygdrivecFoo.
  6. Create an environment variable $MONO pointing to the Mono installation. On 64-bit Windows use this:
    MONO=/cygdrive/c/progra~2/Mono-2.10.8

    On 32-bit:

    MONO=/cygdrive/c/progra~1/Mono-2.10.8

    The point here is to use the DOS short filename compatibility feature to point to the right Program Files (or Program Files (x86)) directory without creating a path with spaces in it, which mkbundle doesn’t like.

  7. Add Mono’s bin directory to your $PATH so you can run mkbundle:
    export PATH=$PATH:$MONO/bin
  8. Add Mono’s lib/pkgconfig directory to your $PKG_CONFIG_PATH environment variable. Usually this starts out empty so just do:
    export PKG_CONFIG_PATH=$MONO/lib/pkgconfig
  9. Now here is the magic part that makes this far less laborious — specify a value for $CC that invokes the mingw32 version of GCC:
    export CC="i686-pc-mingw32-gcc -U _WIN32"

    See, Cygwin used to bundle a version of GCC that supported the -mno-cygwin flag to produce executables that didn’t need cygwin1.dll. The GCC 4.x it includes does not support it any longer. That is why you have to install the gcc-mingw package. Since some people may also have normal gcc installed in Cygwin, I want to unambiguously refer to the mingw32 version of GCC.

    The -U _WIN32 basically removes the predefined _WIN32 preprocessor definition before GCC compiles the C code that mkbundle generates. The Win32 code path in that generated code is broken right now (it uses an undefined function g_utf16_to_utf8 that looks like it comes from glib.) Luckily it works if you turn off that code path — the only thing you will miss is supporting Unicode command line arguments. If this is a problem you can use the more complicated procedure from this StackOverflow post to intercept the C code before it is compiled & fix it yourself. That post doesn’t describe how to fix the UTF thing, but it lets you edit the generated C code before recompiling it.

  10. Now you can finally run mkbundle. Replace the assembly names as necessary:
    mkbundle YourGame.exe OpenTK.dll --deps -o Output.exe
  11. Copy mono-2.0.dll into the current directory since the resulting EXE you just created depends on it:
    cp $MONO/bin/mono-2.0.dll .
  12. Now hopefully your app will run!
    ./Output.exe

    You just have to distribute the output EXE file alongside mono-2.0.dll and it should just magically work on any Windows PC.

Making a reusable script

I have combined all of these steps into a shell script here: https://gist.github.com/3005371. Once you have this as a script, you can recreate the bundle in one step whenever you want. Note that you will have to customize the script a little for it to work for your exact case.

How big is it?

You may be wondering how big your Output.exe and mono-2.0.dll are, seeing as it’s pulling in a Mono runtime and a bunch of System assemblies and so on.

Well, in my test app, which just uses OpenTK to do some OpenGL drawing, the file sizes are as follows:

Output EXE: 13.4 MB
mono-2.0.dll: 2.6 MB
Both of the above, zipped at highest compression: 5.6 MB

5.6 MB is not bad at all compared to the size of textures and music you are likely to include in a game!

Making it even smaller

If you want the EXE file to be smaller even after it is unzipped, you can pass the -z flag to mkbundle and it will compress the embedded assemblies. (That is what the mingw-zlib* Cygwin packages are for.) This will make the EXE file smaller, although it may make startup times a little slower. That took my example EXE from 13.4 MB to 4.6 MB. Of course, now it won’t compress as much when you zip it.

There are also “linker” tools, like monolinker, that can strip assemblies so only referenced code is used. For example, if I only used OpenGL and not the OpenAL functionality of OpenTK, it could theoretically remove the OpenAL stuff from the OpenTK assembly automatically. In practice, it’s not so simple. I tried using monolinker and could not get it to work — it just made an OpenTK assembly that crashed when you tried to use it. I suspect monolinker got a little overzealous and removed something that was necessary. If I could get this to work it would reduce the executable size even further.

But, honestly, I think the executable is small enough already. Any further compression would be nice, but is not necessary.

Extra DLLs required sometimes?

The TODO file in the mkbundle source suggests that these DLLs may also need to be distributed with your program:

  • libglib*.dll
  • libgmodule*.dll
  • libgthread*.dll
  • iconv.dll
  • intl.dll
  • zlib1.dll

My program does not seem to require them, but if you use more framework functionality they may be required. I can see Atom Zombie Smasher includes some of them (specifically libglib and libgthread.) These libraries appear to all be either LGPL, X11 or zlib licensed. You may want to double check the exact terms of the licenses yourself, but it seems like it will just be fine to copy them out of the Mono bin directory and include them with your app.

Next steps

The mkbundle tool works out of the box on Ubuntu for me, and I am going to investigate the options for making a native-looking OS X application eventually as well.

If I have time I will try to submit a patch to Mono so mkbundle “just works” on Windows (provided a Cygwin install.)

52 thoughts on “Using Mono to avoid depending on the .NET Framework on Windows

  1. Sorry for the late response — I haven’t tried this yet, I will look into it if I have some time.

  2. I’m using i686-pc-mingw32-gcc (GCC) 4.7.3 within cygwin (update to Aug. 12, 2013)
    And still reports:
    i686-pc-mingw32-gcc: error: unrecognized command line option ‘-mno-cygwin’

  3. I see a lot of interesting posts on your website. You have to spend
    a lot of time writing, i know how to save you a lot of work, there is a tool that creates unique, google
    friendly posts in couple of minutes, just type in google – k2 unlimited content

  4. Regardless of what stands out as the type of
    necklace, it has too pick the design and style through the dress.
    After thhe interview they were kind enough to give
    mme pointers. When combined, those two nucleation innovations are astounding
    developments.

  5. When I was stuggling difficult to make money on-line, I tried various websites and forums to get difficulty solved. But soon after paying 3 weeks I was not anle to uncover even a single website which couold fix my issue. So I began asking from some of my close close friends who had been always there to assist me. With the help of them and their useful suggestion I identified a single wonderful device which could help me to make material at free of charge of cost unlimited instances. This software demands a single time payment and you can use it for your lifetime.

  6. Thanks , I’ve recently been looking for information approximately this subject for a while and yours is the best I have came upon till now. But, what concerning the conclusion? Are you sure about the supply?|What i do not realize is actually how you’re not actually much more well-liked than you may be now. You’re so intelligent.

  7. Great weblog here! Also your site quite a bit up fast! What host are you the use of?
    Can I get your affiliate hyperlink in your host?
    I wish my web site loaded up as quickly as yours lol

  8. It’s awesome in support of me to have a web page, which is helpful designed for my know-how. thanks admin|

  9. I am trying to compile a vb.net exe uing mono from cygwin terminal here is the complete error run

    $ ./sbox3.sh
    OS is: Windows
    Sources: 1 Auto-dependencies: True
    embedding: D:\__209151\swareDevp\vs12\vb12\SecureBox\SecureBoxV2\SecureBoxV2\bin\Debug\SecureBoxV2.exe
    config from: D:\__209151\swareDevp\vs12\vb12\SecureBox\SecureBoxV2\SecureBoxV2\bin\Debug\SecureBoxV2.exe.config
    embedding: C:\progra~1\Mono\lib\mono\4.5\mscorlib.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Microsoft.VisualBasic.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Mono.Security.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Configuration.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Xml.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Security.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Windows.Forms.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Drawing.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Mono.WebBrowser.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Mono.Posix.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Runtime.Serialization.Formatters.Soap.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Accessibility.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Data.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\Mono.Data.Tds.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Transactions.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.EnterpriseServices.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Xml.Linq.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Core.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.ServiceProcess.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Configuration.Install.dll
    embedding: C:\progra~1\Mono\lib\mono\4.5\System.Management.dll
    Compiling:
    as -o temp.o temp.s
    i686-pc-mingw32-gcc -U _WIN32 -g -o Output.exe -Wall temp.c `pkg-config –cflags –libs mono-2` temp.o
    i686-pc-mingw32-gcc: error: `pkg-config: No such file or directory
    i686-pc-mingw32-gcc: error: unrecognized command line option ‘–cflags’
    i686-pc-mingw32-gcc: error: unrecognized command line option ‘–libs’
    i686-pc-mingw32-gcc: error: mono-2`: No such file or directory
    ERROR: [Fail]

    the .sh file is as under

    set -o errexit
    set -o nounset
    export MONO=/cygdrive/c/progra~1/Mono
    # Required to find mkbundle
    export PATH=$PATH:$MONO/bin
    export PATH=$PATH:$MONO/lib/pkgconfig
    export CC=”i686-pc-mingw32-gcc -U _WIN32″
    mkbundle SecureBoxV2.exe –deps -o Output.exe
    # Copy mono-2.0.dll here since Output.exe depends on it.
    cp $MONO/bin/mono-2.0.dll

    I am badly stuck up and need your help.Please I request if u can spare a bit time to look into the problem.

  10. 逆向直销,震撼来袭:

    优势①:逆向网赚,真正实现就算什么不干都赚钱
    优势②:十级提成,下线年年续费,上线年年收钱
    优势③:静态分红,每日签到就有钱,封顶一百元
    优势④:百万资源,每日更新,一键转存无限下载
    优势⑤:强大网站,八个栏目,无限发布产品广告

    免费注册地址:

    http://www.629494567.9489988.com/

  11. Presume Thin ~ Use hypnosis to re-train your human brain and lose weight normally …
    that is actually ways to get and also remain slim.

    my web site v.gd

  12. A healthy diet is essential to the health of your baby.

    But perhaps most importantly, your baby will
    be safe and comfortable in these bassinets.
    While the bassinet does rock, it has a lock out feature as well.

  13. Wonderful blog you have here but I was wanting to know if you knew of any community forums
    that cover the same topics talked about in this article? I’d really love to be
    a part of online community where I can get responses from other knowledgeable individuals
    that share the same interest. If you have any recommendations, please let me know.
    Appreciate it!

  14. This is an ultra-low-voltage model with 512KB
    L2-cache. Other knee ailments like gout, pseudogout and osteoarthritis affect older people.
    Second, I just like the Chiclet design keyboard though
    I’m not accustomed to it.

  15. Even you may spend a lot of money, never do forget to
    attach a small token of you love for the person with your own hand.
    In fact, LEDs have a longevity exceeding 30 times the Christmas lights glowing.
    Sharing Christmas cakes during the occasion shows our
    due respect to our friends and family as well as the business clients or customers all around the
    globe.

  16. Attractive part of content. I simply stumbled upon your
    weblog and in accession capital to claim that I acquire actually
    loved account your blog posts. Anyway I’ll be subscribing in your augment and even I achievement you get entry to persistently fast.

  17. My brother suggested I would possibly like this website. He wass totally right.

    This put up truly made my day. Youu cann’t consider just
    how much time I had spent for thuis info! Thanks!

  18. For most recent information you have to visit internet and on web
    I found this site as a most excellent site for hottest updates.

  19. Serious moral issues pervade the porn industry,
    such as the exploitation of vulnerable women and
    the enticement of young people—mostly men, but an increasing
    number of women—into an unhealthy sex life that can interfere with normal
    sexual development—and a marriage. When shopping online, you just need to sit down in front of the computer, access the Internet and download the porn VOD titles of your choice.
    We need to turn off the TV more and stop wasting time ‘surfing the web,’ and instead, pick
    up an educational book or spend an hour developing a talent, exercising, or working
    on an entrepreneurial venture – these are a few of
    the reasons people are successful, accomplish great things, and acquire much wealth.

  20. SеҺг ց&#6489teг Aгtіқеl!
    Iϲ&#1211 ѕсɦаuе mіг s&#6513Һг
    ցегne Ѕeгі&#6513n üƄeг ԁaѕ Ιntегnet
    ɑn. Vогallеm mаց ісҺ Max&#8574omе.

  21. Daily intake of saffron milk helps in helping the over all strength of reproductive : and prevents the chance of reproductive disorders like ejaculation problems and erection problems.

    Asthma patients need to take some extrasteps and be more careful.
    The Columbus Asthma Society is anon-profit organization offering treatments likerush immunotherapyfrom best allergy doctors in the Columbusarea including Marysville, Westerville, Delaware , Lancaster, Dublin, Powell,
    Canal Winchester and New Albany.

    My page vitamins & herbs

  22. That is really interesting, You’re an excessively skilled blogger.
    I have joined your feed and look ahead to looking for extra of your great post.
    Also, I have shared your site in my social networks

  23. El artículo Reclutamiento dos.0: Un nuevo escenario en los Recursos Humanos” fue generado en la mesa de trabajo de Recursos Humanos de IAB México, en la cual participan activamente empresas socias como ADTZ, Central Media,
    Códice, Conjunto TV Promo, Leo Burnett, Millward Brown, Nurun, OCC Mundial, Prodigy MSN y Socialand.

  24. WEBSITE POSITIONING: The net marketer is the one with
    the information and ability to get the job achieved.
    But no matter how many years they have underneath their belt, their answer
    isn’t at all times the best one for any explicit website.
    Give me two websites built on the identical platform in the identical industry and I’ll show you a hundred variations between them that
    impression their advertising campaigns.

    My page: Magic Submitter Review, Buy Magic Submitter,
    Magic Submitter Software (http://www.clasificados.com.ni)

  25. whoah this blog is great i love reading your posts.
    Keep up the good work! You realize, many people
    are hunting round for this info, you can help them greatly.

    Breslan Law
    1127 Plainfield Rd
    divorce attorney joliet il (Johnny), IL 60435
    (815) 726-7950

  26. Thanks for your marvelous posting! I seriously enjoyed reading it, you might be a great
    author. I will remember to bookmark your blog and may come
    back divorce attorney in shorewood il (Chana) the foreseeable future.
    I want to encourage continue your great work, have a nice afternoon!

  27. For some time I just constantly presumed the group that victories doings this simply due to the fact that they are physically better,
    however I understand now that this is not the case. It
    is that other quality that propels a group to victory.
    It could likewise do so for your company.
    We’ll get to more on that in a moment.If you really wish to develop an online Affiliate illinois marketing agencies
    (Amber) business that will enable you to generate income from home, you need to do some “set it and forget it”
    type marketing. Some examples of this would be YouTube Videos, ezine articles, Bing
    and Google ads, blogs, and Solo advertisements. By doing this
    you can really set up a totally automated online business.I have actually been in this company for some time and do need to
    say I have built some terrific relationships. These friendships are with a few of the highest caliber,
    intelligent, and friendly individuals you will certainly ever
    meet. I presently have pals all over the world that I can speak with on Skype (likewise totally free) whenever I desire.
    While you might have a house Web company, it’s not such
    as burying yourself in a cave and never ever speaking to anyone ever again. My challenge to you
    is to go make 30 pals a day and introduce yourself, strike up a conversation, and make it count.
    Act beginning now!Possibly you have not been marketing
    that regularly and only doing it on and off during your downtime.
    After a few weeks, you start believing that you’re not getting the traffic and the outcomes you
    want.Banner advertising – A great deal of individuals believe that banner marketing
    is disappearing since no one want to be offered to. No person want to see
    “banner” of individuals attempting to sell them something.
    You have to offer something real, genuine and make your ad
    blend into the rest of the material of the advertising.
    You can acquire truly inexpensive banner all the method to really pricey
    banners.Lastly the 3rd method you can get paid and make money through affiliate programs is
    when you are paid per sale or lead. This is the payment scheme with the greatest dollar
    value. You just earn if your visitors click through the banner on your internet marketing site
    and either sign or buy a product up for a service.Reviews
    on your website make you look good. Ask your most trusted clients to offer testimonials on your site about all the
    terrific things you have done for them. Ideas you can provide them are the consumer support your supply, the easy to utilise website
    content you have, or their general experience with the website.Again, picking
    up from the wrong instructors will certainly get you captured in a circle of failure!

    When it concerns finding out online advertising abilities,
    make certain that you are picking up from someone who has great credibility.

  28. If you were raised in America, then you undoubtedly
    had a youth where you experienced salespeople coming to the door.

    How did your moms and dads respond to that? What type of comments that they make about
    salespeople?Examine your house’s curb appeal and make some improvements.
    Your houses ought to be appealing enough that house hunters would
    believe it deserves buying. Do not settle for a mediocre appearance.
    Put in the very best devices and brighten your home. The point is to make your home stand out.
    And the very best you can do is to highlight the very
    best locations of your house.Both
    short and long term loans are on the offer. Long term loans are essentially for performing long-lasting approaches of a business.
    They are, by nature, buoyed up by not having very accurate payment provisions.
    Nor are they handicapped by having pay-by-date.
    Wait until your business sees a significant enhancement then start paying.
    Only do not take all your life. Small businesses can take the loans to look after short-term uses and pay back whenever there
    is money enough to repay.This technique includes 3 action steps.
    Of course within the steps, there are smaller
    steps, however if you already a possess a little internet marketing experience, you can execute this strategy quickly.
    Okay, lets begin with the steps.Blogging for cash is a simple task that
    will certainly require you to post the blogs and discussing item, brand,
    or any word that might relate a site or supported
    an item, brand or its web website. In turn, they will
    pay you for advertising them. This is very easy because all you
    require to do is produce a blog, post it somewhere
    extremely appropriate or in your own blog-site.Ask a lot of questions.
    Do not be positive with just one response. The only way you can learn the reality is if you ask concerns internet marketing agencies il (Dong) until you
    get to the bottom of things.When you could anticipate a bidding war on your
    piece of home, gone are the bubble days. Today, expect intense haggling and plenty of compromise.
    A residential real estate expert can help assist you through
    the process to help you reach an affordable deal.
    So when you do set the cost for your home, be prepared for it to drop considerably.I am included with advertising online and I also just recently started my
    own vending business in Ottawa called “Food For Thought Beverage Service.” When where you might
    very well be right now in your own life, I was.
    All I can say is have a little faith in yourself.

  29. If yоս aгᥱ ɑ citіzn of Βritіѕһ іѕleѕ and ɑЬօut 18 ʏеaгѕ оf ɑɡе, үyоս can ᥙѕѕе fⲟг tҺе 6 thіrt ɗaу ρᥱгіοԁ financіal ⅼοans no cгеԀіt ѕcߋге cɦeϲҝ օut.
    Іf ʏߋu арpⲣlу
    fоr a lіne of crᥱԀіt, thе ⅼᥱnder ⲟг Ϲгеɗіt Ϲomрany wіll геգᥙеst tҺiѕ гᥱрߋгt.
    TҺе mߋѕt іmрοгtant
    tҺіng іs that Μɑгκеting Ⅿatегіalѕ Ꭰіѕtrіƅᥙtiоn іѕѕ vᥱгүү ϲߋѕt еffеϲtiνe and ɑ ƅսѕіneѕѕ сɑn еɑѕiⅼү ɑϲhіeνе іtѕ tаrɡеt ѕaⅼеѕ ɑаnd іncrᥱasᥱ tһeіг ргоfіtѕ.

    Μʏ ԝеƅ ρaǥе ::
    Rеρоѕѕеsѕіօn Տοftwaгe [http://www.yardeloros.ru]

  30. Outras profissões porquê jornalismo, história, filosofia também podem transportar-se para
    se tornar bons profissionais da extensão com educação sexual porque podem
    estudar modo mais adequado de enviar a respeito de sexo e a
    sexualidade (jornalismo), sobre essa história da luxúria
    (uma vez que os estudos a Foucault) ou do ponto desde vista filosófico.

  31. Nice post. I was checking constantly this blog and I am inspired!
    Very useful info specifically the final section :) I handle such info a
    lot. I was seeking this certain info for a very long
    time. Thank you and good luck.

  32. They may not have enough evidence against you to obtain the search warrant.
    People knowingly or unknowingly suffer from several charges
    like drug charges, traffic violations, illegal possession of weapons
    and ammunitions, prostitution and solicitation, trespassing, resisting arrests, tourist
    crimes, violation of probation, early termination of probation, sealing and expungement, bond hearings and reductions, personal injury and
    many more. You will be really troubled if you are caught for committing any crime and you will
    be having only one way to get rid of the charges by fighting the case with the help of a criminal defense attorney Orlando.
    Serious crimes like felonies are tried to juries of twelve people and the jury must be unanimous in its verdict
    to either convict or acquit the defendant.
    Any person who fails to retain the legal services of a criminal defense attorney may suffer harsh consequences sought by the tough prosecution.

  33. What is Cialis? Cialis (tadalafil) relaxes muscles base in the walls of blood vessels and increases blood rush to itemized areas of the body. http://cialis.withoutadoctorprescriptions.com/ cialis without a doctor’s prescription is toughened to regale erectile dysfunction (helplessness) and symptoms of benign prostatic hypertrophy (enlarged prostate). Another manufacturer of tadalafil is Adcirca, which is cast-off to treat pulmonary arterial hypertension. Do not select Cialis while also fetching Adcirca, unless your doctor tells you to.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>