Building a C++ XPCOM Component in Windows

Note: this post was written in 2011, it quite possibly no longer works in the latest version of Firefox.

I’ve been teaching myself to write Firefox extensions for the last few weeks, and became interested in XPCOM components. Unfortunately, I couldn’t find a good (and recent) summary of them, and had to spend 3 or 4 days cobbling together various tutorials, so I figured it’s time to write one.

What is XPCOM?

XPCOM is a language-agnostic communication platform used in Mozilla products (and some other random pieces of software) to allow code (specifically extensions) to be written in a wide variety of languages.

Why would I want to use XPCOM?

There are two ways to “use” XPCOM. First, you can call functions through XPCOM. For example, the Firefox bookmarks service uses an XPCOM interface. So in order to interact with this service from Javascript you would do something like:

var bmarks = Components.classes[";1"].getService();

There are plenty of tutorials on doing this as it is the more common use for XPCOM, so I won’t go into any detail on it here.

The second way is to write an XPCOM service. That is what this tutorial covers. Sometimes you need extra functionality, speed, or just want to tie into some library that requires a different language. Most commonly this is C++, but there is also JavaXPCOM and PyXPCOM (and probably a few others). I’ll be talking about C++, since it’s what I needed for my project.


  1. Before you trudge through this: you most likely are in the wrong place. Firefox extensions are usually all Javascript. If you can use JS to do what you want, stop now. There is no need to go through the complexity of an XPCOM component when you can just use JS. Go read a tutorial about writing extensions and get to work.
  2. There is something called ctypes coming to FF 3.7 that may make doing this a lot easier. I haven’t touched this at all, but it may be worth considering if you can wait for the functionality and only need to tie into a particular DLL for some functionality. Long story short, XPCOM may become the more difficult way to call C++ functions from FF extensions.

My Setup

  • Windows 7
  • Visual C++ Express 2008 (free from Microsoft’s website)
  • Firefox 3.6 (Gecko 1.9.2)
  • A UUID or GUID generator. This is a unique (read: random) ID that identifies your app to the world. Windows and Linux have tools to generate this (guidgen & uuidgen, respectively), or you can find various online generators (Mozilla links to several). I recommend this one since it gives you the C++ encoded form too, which you will need. You need two different UUIDs: one for your interface and one for your component.
  • Ability to read and understand C++

Sample Code

If you don’t want to go through the tutorial and just want everything to work, then download this sample code. Just follow step #1 of the tutorial, then make sure your Gecko SDK directory is set right in the build step, and you can breeze on by most of this article.

The Tutorial

This is mostly paraphrased from Alex Sirota’s great tutorial, but it hasn’t been updated since 2005 and is a bit outdated. This new one should work out of the box for FF 3.6.

This tutorial will create a component called MyComponent with one function: Add, which will take 2 numbers and, surprisingly, return the sum.

  1. Download the Gecko SDK for your version of Firefox. I used 1.9.2 for FF 3.6.
  2. Create an idl file – IMyComponent.idl, with the following (replacing ***IUID*** with your interface UUID):
    #include "nsISupports.idl"
    [scriptable, uuid(***IUID***)]
    interface IMyComponent : nsISupports
      long Add(in long a, in long b);

    This file is a language-agnostic interface definition which you can read more about here.

  3. Generate the interface header and typelib files out of the interface definition file. Assuming you extracted the Gecko SDK to C:\xulrunner-sdk\, run the following commands (from the directory you saved IMyComponent.idl to):
    C:\xulrunner-sdk\sdk\bin\xpidl.exe -m header -I C:\xulrunner-sdk\idl .\IMyComponent.idl
    C:\xulrunner-sdk\sdk\bin\xpidl.exe -m typelib -I C:\xulrunner-sdk\idl .\IMyComponent.idl

    These will create IMyComponent.h and IMyComponent.xpt, respectively.

  4. IMyComponent.h has two snippits of code that you can use for the next two files. Everything between /* Header file */ and /* Implementation file */ can be used for MyComponent.h:
    1. Start by inserting double inclusion protection code and the right include:
      #ifndef _MY_COMPONENT_H_
      #define _MY_COMPONENT_H_
      #include "IMyComponent.h"
    2. Add the following lines, which define your component name, contract ID, and CUID (where ***CUID*** is the C++-style component UUID, of the form { 0x12345678, 0x9abc, 0xdef0, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } }):
      #define MY_COMPONENT_CONTRACTID ";1"
      #define MY_COMPONENT_CLASSNAME "A Simple XPCOM Sample"
      #define MY_COMPONENT_CID ***CUID***
    3. Copy in the snippet from IMyComponent.h, replacing all the instances of _MYCLASS_ with the name of your component (MyComponent).
    4. Finish off the double inclusion protection code with #endif //_MY_COMPONENT_H_
  5. Everything between /* Implementation file */ and /* End of implementation class template. */ can be used for MyComponent.cpp:
    1. Start by inserting the right include:
      #include "MyComponent.h"
    2. Copy in the snippet from IMyComponent.h, replacing all the instances of _MYCLASS_ with the name of your component (MyComponent).
    3. Add some implementation to the Add method. I replaced return NS_ERROR_NOT_IMPLEMENTED; with
      	*_retval = a + b;
      return NS_OK;
  6. Create your module definitions files:
    #include "nsIGenericFactory.h"
    #include "MyComponent.h"
    static nsModuleComponentInfo components[] =
    NS_IMPL_NSGETMODULE("MyComponentsModule", components)

You now have all of the files needed to build an XPCOM component:


Now comes the hard part: getting the damn thing to build.

Building the code

Ok, it’s actually not hard since I’ve done most of the legwork for you. Assuming you’re using Visual C++ 2008 here are the settings you need (again assuming C:\xulrunner-sdk is where your Gecko SDK is). In Project->Properties:

Configuration Properties
    Configuration Type: .dll
      Additional Include Directories: C:\xulrunner-sdk\include
      Preprocessor Definitions: XP_WIN;XP_WIN32;XPCOM_GLUE_USE_NSPR
      Additional Library Directories: C:\xulrunner-sdk\lib
      Additional Dependencies: nspr4.lib xpcom.lib xpcomglue_s.lib

If you put the idl file into your project, be sure to mark it “Excluded from Build” in its properties…we don’t want VS touching it.

Cross your fingers, pray to whatever deity you believe in, and hit the build button. If it didn’t work let me know why in the comments and I’ll try to build a troubleshooting section.

Installing/Testing the Code

  1. Copy two files to C:\Program Files\Mozilla Firefox\components:
    • The DLL the build generated
    • IMyComponent.xpt
  2. Normally, if this was installed as part of an extension, it would automatically search this directory and find these files. But now we have to force a refresh. Delete xpti.dat. and compreg.dat from your profile directory (FF will regenerate them on next restart)
  3. Close Firefox and open it with this test file (MyComponentTest.html in the sample code):
    <script type="text/javascript">
    function MyComponentTestGo() {
    	try {
    		// normally Firefox extensions implicitly have XPCOM privileges, but since this is a file we have to request it."UniversalXPConnect");
    		const cid = ";1";
    		obj = Components.classes[cid].createInstance();
    		// bind the instance we just created to our interface
    		obj = obj.QueryInterface(Components.interfaces.IMyComponent);
    	} catch (err) {
    	var res = obj.Add(3, 4);
    	alert('Performing 3+4. Returned ' + res + '.');
    <button onclick="MyComponentTestGo();">Go</button>
  4. One last time: cross your fingers, pray to whatever deity you believe in, and hit the Go button. If it didn’t work let me know why in the comments and I’ll try to build a troubleshooting section.

Hopefully this clears up what looked like a lot of confusion to me. I will keep this updated to the best of my abilities and hopefully it will continue to be useful for a long time.

64 responses to “Building a C++ XPCOM Component in Windows”

  1. goseas says:

    it’s works as above code when build as release,one more question,
    how to make a serveice or singleton component

  2. Hi I am new in XpCom
    is it suppose to work in mozilla 8.1 ?

    its not working for me :(

    I downloaded the older gecko sdk and followed all the steps as above.
    [because in latest gecko 8.1 sdk so many header files are changed and not getting any
    proper example in web that uses the latest sdk]

    any Idea?

  3. […] LD_AddCustomAttr("AdOpt", "1"); LD_AddCustomAttr("Origin", "other"); LD_AddCustomAttr("theme_bg", "ffffff"); LD_AddCustomAttr("theme_text", "333333"); LD_AddCustomAttr("theme_link", "0066cc"); LD_AddCustomAttr("theme_border", "f2f7fc"); LD_AddCustomAttr("theme_url", "ff4b33"); LD_AddCustomAttr("LangId", "1"); LD_AddCustomAttr("Autotag", "technology"); LD_AddCustomAttr("Tag", "firefox"); LD_AddCustomAttr("Tag", "mozilla"); LD_AddCustomAttr("Tag", "xpcom"); LD_AddCustomAttr("Tag", "firefox-extensions"); LD_AddCustomAttr("Tag", "firefox-plugin"); LD_AddCustomAttr("Tag", "xpcom-extensions"); LD_AddSlot("wpcom_below_post"); LD_GetBids(); Share this:TwitterFacebookLike this:LikeBe the first to like this post. This entry was posted in Firefox, Mozilla, XPCOM and tagged Firefox Extensions, Firefox Plugin, XPCOM extensions. Bookmark the permalink. ← NPAPI Plugin (Must read) How to extract Interface and Property details from NPAPI Windows plugin → […]

  4. ameya says:

    I got this error “TypeError: Components.classes[cid] is undefined ” on hitting GO.
    Plz help me…

    is it working on FF 6?

  5. Michael says:

    How do I get a String return instead of long in this example? Thanks for the help.

  6. elia says:

    I read you XPCOM gide which helped me alot,
    I wrote one for v12 (doc format)
    If u want I will send it to u so that u can upload it to your blog


  7. Shanmugham says:

    Iam a new bee to this XPCOM. COuld you please forward the doc file?


  8. Andrew Polar says:

    This is just another useless site in the long list of others. They all are different but having one thing in common. No matter how careful you follow the instruction that just not damn working.
    I built and registered component and from now on enjoy seeing message:
    TypeError: Components.classes is undefined
    every time I hit the button. That means the component is not recognized. Same result you receive when you did not even create one. There are many people that experience the same bug and there are others that did not see this bug ever. Those that did not see this bug are very surprised and say that they have no idea what is it.
    Look: if you publish instructions you are suppose to be an expert. You must know how people have this bug and how to correct it.

  9. Brian says:

    Sorry Andrew, this was written literally 4 years ago, I’m not too surprised it no longer works in the latest version of Firefox.

    I’ll add a not to the top of the post.

  10. Andrew Polar says:

    Firefox developers quietly changed components directory into “/browser/components/” without notification of anyone other than their friends. But that is not the fix. I tried to place the XPCOM call into fully functioning JS extension that is using the other XPCOM. The result was unsuccessful.
    I have JS file picker code looking functionally identical:

    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes[“;1”].createInstance(nsIFilePicker);
    fp.init(window, “Select a File”, nsIFilePicker.modeOpen);
    var res =;
    if (res == nsIFilePicker.returnOK){
    var thefile = fp.file;
    // — do something with the file here —

    Replacing it by call to MyComponent does not make it working. That means that MyComponent.Dll itself is no longer valid for latest Mozilla browsers.
    By the way, file picker SID;1 is sitting in XUL.DLL, which is in main mozilla folder.

  11. Andrew Polar says:

    I installed FF 3.6.2 and it does not function for it either. Few things are true for this browser. It has /components directory, it has files compreg.dat and xpti.dat and they are restored at each start when removed. But still no result.
    The reason could be in some other system DLLs that are linked to MyComponent.dll. They all evolved during this time.

  12. Andrew Polar says:

    There is no easy way to make HelloWorld application. Even the name “Hello World” must be replaced by something “ItIsDamnHard” project. The reason is arrogance and unprofessionalism among developers of xulrunner. They make changes to code from one Firefox and xulrunner version to another ignoring interests of other developers.
    First change with FF 34.0.5 is that batch file in section 3 is not relevant. You have to install python and use python script to create *.xpt and *.h files.
    Second change is that module code is section 6 must be completely different.
    But that is not all the worst news is that library xpcommglue_s.lib is compiled by xulrunner developers with god knows what visual studio and settings, so it is conflicting with VS2013 and VS2010. The linking errors:

    Error 3 error LNK2038: mismatch detected for ‘_MSC_VER’: value ‘1600’ doesn’t match value ‘1800’ in HelloWorld.obj C:\APOLAR\XUL\helloworld\HelloWorld\HelloWorld\xpcomglue_s.lib(nsISupportsImpl.obj) HelloWorld


    Error 4 error LNK2038: mismatch detected for ‘_ITERATOR_DEBUG_LEVEL’: value ‘0’ doesn’t match value ‘2’ in HelloWorld.obj C:\APOLAR\XUL\helloworld\HelloWorld\HelloWorld\xpcomglue_s.lib(nsISupportsImpl.obj) HelloWorld

    clearly indicate settings conflict for linker. Now I’m thinking what is easier to disassemble xpcomglue_s.lib and correct constants or recompile whole xulrunner.

    I think this blog must be removed because it provides about 1% information that developer actually needs to succeed.

    You can follow the link
    and find comment
    Stefan WintersteinNovember 18th, 2014 at 13:06
    It explains how to make it running for xulrunner 29. You also need FF 29. This is the latest version that I found anyone succeeding in making this damn so called easy project running.

  13. Andrew Polar says:

    I managed to make it running. My comments are at

    I know it is hard to follow, I provided my email for questions.
    If I find time I will write user manual for making HelloWorld XPCOM C++ for version 34.0.5

    I apologize for angry tone in my comments but stand by my statement that developers of xulrunner MUST EXPLAIN EVERYTHING in a clear way. They just MUST even if it is free.

Leave a Reply