Eclipse CDT

Introduction

This page is new, and has been written pretty much from scratch to replace our old Eclipse docs. If you encounter any problems or have any questions, contact Jonathan Watt. So far these instructions have not been tested on Windows.

Eclipse CDT (C/C++ Development Tools) is an open-source IDE for C and C++ development. It supports complex projects that have their own build system, like Mozilla. If you want to use an IDE for Mozilla C++ development with advanced code assistance (inheritance/call graph explorer, jump to definition, refactoring, autocomplete, syntax highlighting, etc.), then Eclipse CDT might be for you.

System requirements

Eclipse provides many features that you'll find yourself unable to live without once you start using it, but it does come with some fairly hefty system requirements. In order to work with a fully indexed Mozilla source tree, Eclipse will use 1-2 GB of RAM. You'll want to have at least 8 GB of RAM installed, or better yet, Eclipse provides you with the perfect excuse to upgrade to 16 GB. :-)

Installing Eclipse

Download Eclipse IDE for C/C++ Developers from the Eclipse download page, extract the file, and put the resulting directory somewhere sensible. Don't open Eclipse just yet.

In case you come across it, note that you should not install llvm4eclipsecdt (or if you do, don't choose its toolchain below), even if you're using clang as your compiler. This plugin is intended mainly for managed projects, but we use an unmanaged project for Mozilla since it has its own build system. (If you do install this plugin and use its tool chain below, then you'll find that parts of the UI that you'll need to access will be disabled.) Instead, just proceed with setting up Eclipse as detailed below as if you were using GCC as your compiler.

Increasing memory limits

When Eclipse's indexer tries to process the Mozilla source, Eclipse will need considerably more memory than it allows itself out of the box. You should increase its memory limits using the eclipse.ini in your installation directory (or in Eclipse.app/Contents/MacOS if you're on Mac). Set something like -Xms1G -Xmx3G -XX:MaxPermSize=1G (initial heap space of 1 GB, max heap space of 3 GB, max perm-gen space of 1 GB).

If you fail to increase these limits then you will likely find that Eclipse hangs when you try to index or work with the Mozilla source later on.

Express setup

Your MOZ_OBJDIR can not live in your source directory. Add and customize the following option to your mozconfig:

mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/../obj-ff-<NAME>

The build system can now generate the eclipse project on your behalf. This replaces the instructions below however you may still want to get familiar with them. To generate the workspace (1) run a complete top level build, (2) run:

./mach build-backend -b CppEclipse

this will take about 30 seconds. The path to the generated eclipse workspace will be echo'd. Open the workspace from eclipse and import the existing 'Gecko' project from the generated workspace.

Setup time

The build system now supports generating Eclipse projects, the instructions on this page should be adjusted accordingly.

You can expect it to take an hour or so to work through these instructions if you're doing so for the first time.

(This assumes that you already have a copy of the Mozilla source, and that you have also built the source so that you have a pre-existing object directory. If that's not the case, then get your build going now so that it can be running while you continue with the instructions below. FAQ: Wait, why does Eclipse need an object directory?)

Code assistance

Out of the box, Eclipse can provide some code assistance for the Mozilla source, but it will be very incomplete and often just plain broken. If you set up Eclipse as detailed below it will do a much, much better job.

Important background

To help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provides some background on what IDEs need in order to provide advanced code assistance, and what Eclipse CDT needs in particular.

To be able to provide really good code assistance for a project's source code, IDEs like Eclipse need to carry out a thorough static analysis of the project's source files to build up a picture of the code (what Eclipse is trying to do when it "indexes" the source.) Static analysis involves parsing the source files, so naturally it can only produce good results if it has a sensible set of preprocessor defines, include paths and pre-include files for each source file. Since Eclipse doesn't initially have any of this information, the code assistance that it's able to provide out of the box is pretty broken.

For projects the size and complexity of Mozilla, it's impractical to manually configuring Eclipse with a valid set of defines and include paths for each of the different parts of the source code. Happily, Eclipse makes manual configuration unnecessary. Like some other IDEs, for projects like Mozilla that have their own build system, Eclipse provides a tool that can collect the options that are passed to the compiler for each file that's compiled during an actual build. This process is sometimes called "build option discovery" or "compiler option discovery".

The way that Eclipse CDT does build option discovery is to scan the console output from a real build looking for lines where a compiler was invoked. For each line that invoked a compiler, it tries to figure out which source file was being built and what its include paths were. If relative paths are used to specify the source file or any of its include paths (common in Mozilla), and if you fail to take steps to make sure the build output specifies which directory the compiler is invoked from, this will not be possible. If Eclipse can successfully identify which source file was being compiled, then it can associate with that file the resolvable include paths, preprocessor defines, and pre-include files that were passed to the compiler.

Note the requirements that this method of build option discovery imposes on us. First, Eclipse needs build console output for a complete build so that it can find compiler options for as many source files as possible. The build must be explicitly instructed to output information that allows the directory that the compiler is being invoked from to be identified (i.e., 'make' must be instructed to output "Entering directory..."/"Leaving directory..." lines). Finally, the build must not be parallelized, since that would result in interleaving of build output from different directories (breaking resolution of relative paths by interleaving the "Entering directory..."/"Leaving directory..." lines), and the build must not be silenced/quietened.

Conversely, note this very carefully: if you configure Eclipse to invoke a build process that is parallelized, silenced, or that fails to identify the directory that the compiler is being run from, then it will mess up the compiler options that Eclipse associates with your files, and that in turn will significantly degrade the quality of the code assistance that Eclipse will provide after it next re-indexes the code.

These requirements aren't a very good fit with the typical Mozilla developer's wish to minimize build times, implying parallelized, silenced builds.

The consequences of the above observations are this:

  • It is strongly recommended that you invoke your normal (re)builds from the command line, externally of Eclipse.
  • Below we will configure Eclipse's build step so that you use it only occasionally to manually trigger a special "build" (actually a fast script that fakes a build) purely for the purposes of setting/updating the compiler options that Eclipse associates with each source file.

(Not using Eclipse to invoke your real builds does lose you some minor benefits that Eclipse has to offer, but these are worth sacrificing for much improved code assistance. See the Building from Eclipse section below if you're interested in what you lose. If you're interested in future improvements to Eclipse that would allow parallel builds to be run from inside Eclipse while still allowing it to obtain the compiler options, see the FAQ Isn't there a better method of build option discovery? below.)

Initial workspace preferences

When you open Eclipse, it will ask you to "Select a workspace" (a directory where Eclipse will store files that it generates during indexing, etc.) It's recommended that you have a separate workspace containing only a single project for each Mozilla source tree [rational], and that you choose a directory outside the Mozilla source. Something like $HOME/eclipse-workspaces/mozilla-tree-1, for example. After selecting an appropriate directory, click OK, then close the "Welcome" tab when the main Eclipse window opens.

Before you proceed any further, check that your changes to Eclipse's memory limits have taken effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration.

To avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below).

Whenever you create a new workspace for a Mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (Window > Preferences, or Eclipse > Preferences) before creating a project in that workspace:

  • in "General > Workspace", disable "Build automatically"
  • in "C/C++ > Indexer", disable "Automatically update the index"

Turning off automatic indexing prevents the CPU intensive indexer from running at various stages during the steps below before we're ready.

Select "General > Content Types", expand "Text > C Source File > C++ Source File", click "Add" and add "*.mm". Eclipse CDT doesn't currently understand Objective-C files (although there is a project that promises to add Objective-C support), so for now this is the best we can do to give Eclipse a chance of expanding its understanding of the source into the Objective-C files.

Select "General > Editors > Text Editors". If you want line numbers, tick "Show line numbers". If you want a column marker to mark the 80th column to help with formatting code to Mozilla's 80 character line limit, tick "Show print margin" and set the value to 80.

Select "General > Workspace" and select "Refresh using native hooks or polling" and "Refresh on access" to prevent Eclipse giving you annoying "Resource is out of sync" messages when files change from under it due to Mercurial or other external activity.

Select "C/C++ > Build > Console" and set "Limit console output (number of lines)" to something large, like "1000000".

Eclipse CDT will try to format C/C++ code that you add as you type. However, its default formats are not a good match to Mozilla's style rules. Download this first pass at an Eclipse formatter configuration for Mozilla C/C++ coding style, and install it by opening the workspace preferences, selecting "C/C++ > Code Style > Formatter", and then using the "Import" button to import that file. The "Active profile" field should then automatically change to "Mozilla". Depending on the area of the code that you work on, you may need to tweak this configuration using the "Edit" button. (Note that the format settings under "General > Editors > Text Editors" have no effect in C/C++ views, since the C/C++ settings are more specific and override those settings. However, you may still want to tweak those settings if you'll be editing other file types in Eclipse.)

Select "C/C++ > Editor" and set "Workspace default" to "Doxygen".

Select "C/C++ > Editor > Content Assist" and set the Auto-Activation delay to 0 so that autocomplete suggestions don't seem to be laggy. (Sadly there is no auto-activation option to activate autocomplete suggestion as soon as you type any alphabetical character that may begin a symbol name like there is in other IDEs.)

Select "C/C++ > Editor > Save Actions" and deselect "Ensure newline at the end of file".

Select "C/C++ > Editor > Scalability" and set "Enable scalability mode when the number of lines in the file is more than:" to something larger, like 100000.

Select "Run/Debug > Console" and deselect "Limit console output".

If you want to increase the text size in the editor, select "General > Appearance > Colors and Fonts", select "Basic > Text Font", and edit the font size.

Creating an Eclipse project

To create an Eclipse project for your Mozilla source tree, select "File > New > Makefile Project with Existing Code". In the "Import Existing Code" window that opens, enter a meaningful Project Name that identifies your Mozilla source tree, set the code location to the root of your source tree, select an appropriate Toolchain (e.g., "MacOSX GCC"), and click Finish.

The status bar at the bottom right of the window should now show that Eclipse is "Refreshing the workspace" (gathering a list of all the files in the source tree). Click on the little green button beside this message to open the "Progress" tab, and keep an eye on the "Refreshing workspace" item as you continue with the steps below. (If an "indexing" item starts after the "Refreshing the workspace" item has finished, click the little red box beside that item to cancel it, since we want to configure the project before the indexer runs.)

Initial project properties

So that the indexer will run faster and give better results, and so that Eclipse doesn't give results for irrelevant files, you should add some resource filters to have Eclipse ignore certain non-source files and directories. Note, you must not make Eclipse ignore your (main) object directory. That object directory is needed to resolve include paths to the various headers that the build process generates/copies there.

To create resource filters, open the project properties (different to the workspace preferences!) by selecting Properties from the context menu for the project (root item) in the Project Explorer tab on the left, or by selecting Project > Properties from the menubar. Select "Resource > Resource Filters" on the left of the window that opens, then use the Add button to add the following filters:

  • Add an "Exclude all" filter for folders with a Project Relative Path matching ".hg". (This directory doesn't show in the Project Explorer tab, but Eclipse still indexes it without this filter!)
  • If you have secondary object directories (object directories that are not your only/the primary object directory) for the source tree and those directories are inside the source tree (or if you might have such object directories in future), then add an "Exclude all", regular expression filter for folders with a Project Relative Path matching "obj(?!-debug(?:$|/)).+". This particular regular expression will exclude all directories beginning with the string "obj" except "obj-debug", so if "obj-debug" is not the name of your main object directory, then adjust the regular expression as necessary.
  • Add a recursive, regular expression "Exclude all" filter for files with Name matching "\.(?:rej|orig|o|pp|swp)$" to exclude .rej, .orig, .pp, .o, and .swp files.
  • Add "Exclude all" filters for any other non-source directories that you've added to your source tree (e.g., Xcode or MSVC project directories).

Click OK to close the filters window, wait for Eclipse to finish processing your resource filters, then make sure the filtered directories and files have disappeared from the Project Explorer tab on the left. Also, if your main object directory is in your source tree, and not somewhere outside it, make sure that it has not disappeared from the Project Explorer tab.

Reopen the project properties window and select "C/C++ Build" from the left of the project properties window. Select the "Builder Settings" tab, untick "Use default build command", set the build command to "just-print-mozilla-build.py" or, if you're on Mac, to "bash -l -c 'just-print-mozilla-build.py'" (on Mac Eclipse doesn't seem to pick up the environment properly, so it's necessary to invoke just-print-mozilla-build.py indirectly through bash). (just-print-mozilla-build.py is a fast script that we'll download in the next section.) (append '--objdir /path/to/objdir' if your objdir lives outside your tree) Set the build directory to "${ProjDirPath}/path/of/your/objdir/relative/to/the/root/of/your/source". Select the "Behavior" tab, delete the word "all" from the "Build (incremental build)" field, and disable the Clean checkbox.

If you can't untick "Use default build command", you have to change the current builder by clicking on "Tool Chain Editor" (in C/C++ Build) and choosing another builder (e.g., "Gnu Make Builder").

If you will not be using Eclipse for debugging, select "C/C++ Build > Settings" on the left, select the "Binary Parsers" tab, and make sure that all the parsers are deselected. This prevents the (useless if not debugging) "Searching for binaries" action from constantly interrupting everything.

If you will be using Eclipse for debugging, select "C/C++ General > Paths and Symbols" and select the "Output Location" tab. You should now add the folder containing your firefox binary (note on Mac this is inside the .app - so "{your-obj-dir}/dist/NightlyDebug.app/Contents/MacOS/" - and since the UI will only allow you to select to the 'dist' folder, you'll need to type the end of the path in manually). How you add this depends on whether your object directory is inside or outside your source tree. If inside, use the "Add Folder" button; if outside, use the "Link Folder" button and tick the "Link to folder in the file system" checkbox. Once you've added this folder, delete the existing output folder that was set to the root of the project. Doing this prevents the "Searching for binaries" which Eclipse constantly starts from taking too long.

Select "C/C++ General > Preprocessor include Paths, Macros etc." Select the Providers tab. Make sure that "CDT GCC Build Output Parser" is selected, and that "CDT Managed Build Settings Entries" is not selected. Highlight (select) "CDT GCC Build Output Parser", then in the "Language Settings Provider Options" that appear below, make sure that "Share setting entries between projects (global provider)" is not ticked.

If the main object directory for your source tree is a Fennec build: In the "CDT GCC Build Output Parser", change the compiler command pattern to

(.*gcc)|(.*[gc]\+\+)|(clang)

(before this change it should have been "(gcc)|([gc]\+\+)|(clang)"). This pattern is what CDT uses to identify compiler commands when parsing the build output. By default, it recognizes commands of the form "gcc", "g++", "c++", and "clang". This is fine for a desktop build, where the commands are in fact "gcc" and "g++". For Fennec builds, however, most of the commands are something like "arm-linux-androideabi-g++", which will not be recognized by the default regex. The modified regex accepts any command that ends with "gcc" or "g++". This may also affect other non-desktop builds besides Fennec.

Especially important if the main object directory for your source tree is located somewhere outside your tree's top source directory: If this applies to you, then select the Entries tab, select "GNU C++", select "CDT User Settings Entries", and click "Add". Change "Project Path" to "Filesystem", then select the 'dist/include' directory that's in your main object directory and click OK. Repeat these steps, but this time for "GNU C" instead of "GNU C++". (See the Headers are only parsed once section below to understand why this step is important for people who have their object directory outside their source tree.)

Getting code assistance working

You're now ready to get code assistance working. :-)

Build option discovery

This section requires that you have already built your mozilla source tree (so that you have an object directory for it), and it is strongly recommended that the object directory is up to date so that the just-print-mozilla-build.py script runs quickly.

As explained in the Code assistance section above, to provide good code assistance Eclipse CDT needs to collect build information for the source files by processing a build log from a full, clean build made using -j1 -w. Since such a non-parallel, full build would take a very long time, we're going to cheat and set Eclipse's "Build" action to run jwatt's just-print-mozilla-build.py script instead. This script will complete in about 30 seconds on a warm tree (files cached in RAM) if your object directory is up to date, although Eclipse will take several minutes to process the "build output" that it produces.

Download just-print-mozilla-build.py and change its permissions to make it executable ('chmod a+x just-print-mozilla-build.py').

If you don't put just-print-mozilla-build.py somewhere in your PATH, then go back to the Initial project properties section where you set just-print-mozilla-build.py and specify its absolute path instead of just its name.

Now invoke the script by clicking the Build button (the button with the hammer symbol) or by selecting "Project > Build Project" from the main menu. That done, select the "Console" tab at the bottom of the main Eclipse window and you should see the build console output flying by as Eclipse processes it. It should take about 5-10 minutes for Eclipse to finish processing the output.

Additional discovery for C++11 mode

As of Mozilla 25, Mozilla is built in C++11 mode. When GCC is invoked in C++11 mode, it defines preprocessor symbols that enable conditional compilation of C++11 code in its standard library. To correctly parse this code, Eclipse CDT needs to know about these symbols. Unfortunately, the build option discovery process outlined above does not pick up this information, so CDT needs to be told separately about C++11 mode. To do this, go to "Preferences -> C/C++ -> Build -> Settings -> [Discovery] tab -> CDT GCC Built-in Compiler Settings" and add the flag "-std=c++11" at the end of the field labeled "Command to get compiler specs".

In CDT 8.3 (unreleased as of August 2013), there will be a more user-friendly way to specify this (see http://wiki.eclipse.org/CDT/User/NewIn83#Toolchains).

Building the index

Once you see the end of the build output in the Console tab and the Build item has disappeared from the Progress tab, you can start indexing the source. If indexing started automatically (see the Progress tab), cancel it, since there seems to be a bug that makes it give bad results when it starts automatically at this stage. Right click the project root in the Project Explorer tab and select "Index > Rebuild". You will now see "Indexing..." in the status bar at the bottom right and an Indexing item in the Progress tab. It will take 10 minutes or so on a decent developer machine for a full rebuild of the index.

Once the indexer has finished (keep an eye on the Progress tab), sanity check that everything went as it should have by right clicking the project in the Project Explorer tab and selecting "Index > Search For Unresolved Includes". If you get many more than 2000 unresolved includes (as of May 2012), then things have gone pretty wrong. You should be able to use the list of unresolved includes to help figure out what the problem is (see also the Parser errors section for more troubleshooting tips).

Assuming everything went as expected, you should now find that Eclipse's code assistance works a whole lot better. :-) To test out the code assistance, see the Code assistance subsection of the Usage tips section below.

To improve code assistance even more, see the Headers are only parsed once subsection of the Known Issues section.

Keeping the index up-to-date

As the source changes from day-to-day, you'll want to update the index to keep the code assistance working well.

Since the compiler options used to build the source change relatively infrequently, the "build" step above doesn't need to be rerun all that often. Rerun it (and then rebuild the index) once a week or so, or as necessary when you start to notice unusual code assistance issues that aren't fixed by rebuilding the index alone.

Rebuilding the index itself is required much more frequently since the source changes more frequently. In principle you can set the index to rebuild automatically by opening the workspace preferences, selecting "C/C++ > Indexer", and reenabling "Automatically update the index". However, you may find this too disruptive, since reindexing will then happen very frequently and code assistance can be broken while the index is rebuilding. The alternative is to leave that option disabled and update the index manually as necessary. To update the index manually, use the context menu in the Project Explorer tab on the left side of the window. To rebuild for changes in an individual directory (for example, to take account of some changes that you yourself made) select "Index > Freshen All Files" on that directory. To rebuild the entire index (for example when you pull from mozilla-central) select "Index > Rebuild" on the project root.

Usage tips

Below are some of the more useful user tips. (If you're thinking of adding tips, please first consider how widely useful they'll be before adding to this already lengthy page.) For further documentation see the official Eclipse user guide and Eclipse CDT user guide.

Keyboard shortcuts

Regarding key bindings (keyboard shortcuts), the bindings given below are the defaults. You can change the key bindings by opening the workspace preferences (Eclipse > Preferences, or Window > Preferences) and selecting "General > Keys". You can set the scheme to "Emacs" or "Microsoft Visual Studio" if that's your thing, or change individual key bindings. When changing individual key bindings, note that bindings are context sensitive, and that any changes you make may be ignored if they conflict with existing bindings or if they are overridden by a binding for a more specific context. For example, changing the Find Next command to cmd-G/ctrl-G is not sufficient. For that to work you also either need to find the existing bindings for that key combination (using the Bindings column to sort by key combination helps with this) and remove them, or else you need to make your binding very specific by setting the "When" field to "C/C++ Editor" instead of the more general "Editing Text".

Opening files

You can quickly open a file by name using Cmd-Shift-R/Ctrl-Shift-R. Although Eclipse doesn't do fuzzy matching when you type a file name, it does allow you to use wildcards.

To quickly switch between a source file and its header file, use Ctrl-Tab.

To quickly switch to a recently viewed document use Cmd-F6/Ctrl-F6. If you want to change this awkward key binding, the command you need to rebind is "Next Editor".

To show a filterable list of open documents (similar to the way Emacs gives you a list of open buffers), use Cmd-E/Ctrl-E.

If you click the yellow, double arrow button at the top of the Project Explorer tab on the left, it will keep the selected file in the Project Explorer tab in sync with the file that you're currently editing.

Organizing views

Use Ctrl-M to toggle maximization of the current editor view (the editor must be focused first).

To tab to another view, use Cmd-F7/Ctrl-F7. This is useful if you have maximized the editor using Ctrl-M and you want to quickly see your search results, for example, without un-maximizing the editor.

To side-by-side edit the same file in two different tabs, select the tab of the file that you want to edit, then from the menu bar select "Window > New Editor". This will open another tab containing the same file. Now simply drag that tab to position it beside, above, or below the original. Changes you make in one editor will be immediately reflected in the other.

Note that the Search, Call Hierarchy, etc. tabs have a "Pin" button that allows you to open multiple tabs of these type. This is useful if you want to keep your existing search results open, for example, and have a new search open in a separate tab rather than overriding the contents of the existing Search tab.

Code assistance

Note: indexing, by its very nature, is specific to a given compiler configuration. Be aware that when Eclipse gives results for any of the actions that follow, it will not include results for sections of the code that are ifdef'ed out by the configuration used to create your object directory. For example, if you are using a Mac and you search for callers of nsDisplayListBuilder::IsInTransform, the results will not include the caller in nsObjectFrame.cpp because that caller is wrapped in "#ifndef XP_MACOSX". Just something to keep in mind. ;-)

To jump to the definition of a symbol (or the declaration of a symbol if already at the definition), hover over the symbol, hold down the Ctrl/Cmd key, move the mouse slightly to linkify the symbol, then click on it. (Having to move the mouse slightly is Eclipse bug 26873). Alternately, you can jump to the definition of the symbol under the cursor by pressing F3.

To do a C++ symbol search select "Search > C/C++" from the menubar, or use Ctrl-H and select the "C/C++" Search tab.

To quickly find the definition of an enum, class, method, etc. use Ctrl-shift-t/Cmd-shift-t.

To get a list of autocomplete options in an editor tab, start typing the name of an identifier and then type Ctrl-Space. Unfortunately the autocomplete list cannot (currently) be configured to appear automatically as soon as you start typing a character that might be the start of an identifier name.

To see the callers of a method (and their callers, etc.), select the method and use the context menu to select "Open Call Hierarchy". Note that there are buttons to the right of the "Open Call Hierarchy" tab that open to switch between "Show Callers" and "Show Callees".

To see the inheritance tree for a class, select its name in an editor window and select "Open Type Hierarchy" from the context menu. Note that you can switch between "Show the Type Hierarchy", "Show the Supertype Hierarchy", and "Show the Subtype Hierarchy" using the buttons to the right of the "Type Hierarchy" tab.

To see the overrides of a virtual method, select that method's name in an editor window and select "Open Type Hierarchy" or "Quick Type Hierarchy" from the context menu. The results for "Open Type Hierarchy" will show all classes in the class inheritance tree, and the classes that have methods that override the method will have a triangular red marker beside them. If you select one of these classes then in the method pane to the right the method you searched for will be highlighted (you may need to scroll to it) - double click to see its definition. The results for "Quick Type Hierarchy" will only show those classes in the inheritance tree that override the method. Double click on a class to go straight to its override's definition.

Building from Eclipse

In short, don't do this. Eclipse doesn't have good facilities for building incrementally in individual directories in the way that Mozilla developers generally require. More importantly, unless you're willing to screw up Eclipse's code assistance (in which case why bother using Eclipse) you're going to have to set Eclipse's "Build" step to do a very slow, non-parallel, full rebuild. (See the "Code assistance" section above for why.)

Nevertheless, if you understand the above warning and you still want to configure Eclipse's "Build" button to invoke a real build, then read on.

Basically you want to do something similar to the steps in the Initial project properties section above, but use "make -j1 -wB" (or just "make" if you don't care about keeping code assistance working) instead of using just-print-mozilla-build.py.

If you want to invoke "make -f client.mk" from your source directory instead of invoking 'make' from your object directory, then in the "C/C++ Build" section of the project properties, set "Build command" to "make -f client.mk" and set "Build directory" to just "${ProjDirPath}" (this is the top of the source tree). Select the Behavior tab and remove the "all" from the "Build (Incremental build)" field. Select "C/C++ Build > Build Variables", and add a variable "MOZCONFIG" and set it to the path of your .mozconfig file relative to the top source directory. Set any other environment variables you want to set for the build, then close the project properties window.

Now when you hit the Build button (the little hammer icon) you should see the source build in the Console tab at the bottom of the window.

The benefit of building from inside Eclipse is that build errors will appear in the Problems tab at the bottom of the window, and from there you can double click on the build error and it will take you straight to the source file and line where the problem occurred. For this to work reliably though, you still need to build using slow -j1 -w builds so that make outputs non-interleaved "Entering"/"Leaving" lines. It also used to be necessary to add the following two lines to your mozconfig to make the compiler output errors all on a single line, but that may not be needed any more:

export CFLAGS="-fmessage-length=0"
export CPPFLAGS="-fmessage-length=0"

Debugging

To create a debug configuration, open the project properties window, and select "Run/Debug Settings" on the left. Click "New", then select "C/C++ Application". In the window that opens enter the path to your firefox binary (something like {your-obj-dir}/dist/NightlyDebug.app/Contents/MacOS/firefox) and select "Disable auto build". Select the Arguments tab and enter any args you want to pass to firefox (such as "--no-remote -p my-testing-profile"). If you're on Linux, you may also need to set the "Working directory" to {your-obj-dir}/dist/bin, and then select the Environment tab and set LD_LIBRARY_PATH to ".:./plugins:." and LIBRARY_PATH to ".:./components:.". (Are these variables really necessary? If so, why? Isn't LIBRARY_PATH for compile time, not runtime, linking?)

In the workspace preferences, you may want to go to "C/C++ > Debug > GDB" and deselect "Stop on startup at" so that Eclipse won't automatically break in main() when it launches Firefox for debugging.

To debug, click the Debug button on the toolbar, or select "Run > Debug" from the menu bar.

It's not obvious, but you can get a gdb prompt in the console so that you can type gdb commands directly.

After you've finished debugging, you can get back to the C/C++ perspective (i.e., window layout) via the menubar by selecting "Window > Open Perspective > C/C++".

Upgrading GDB on Mac

The ancient, barely maintained Apple fork of GDB that comes with Xcode on Mac is really horrible. If you use Mac, you may want to build the latest FSF version of GDB and set Eclipse to use that GDB for debugging. One suggested configuration for building GDB is '--prefix="$HOME" --disable-debug --with-python=/usr' (create an optimized build with support for Python (so that you can use python to much better control when you break etc.), and install it in $HOME/bin). That done, open the workspace preferences, select "C/C++ > Debug > GDB", and set "GDB Debugger" to the full path of your new gdb executable.

GDB unexpectedly detaching

If GDB starts ignoring your breakpoints, or unexpectedly terminates or detaches from the Firefox process, this may be caused by out of date breakpoints (breakpoints that you set during a previous debug session, after which you've since rebuilt). Remove any such breakpoints and restart your debug session.

Known Issues

There are various known limitations and bugs when it comes to using Eclipse with Mozilla. Eclipse is open source, of course, so if anyone feels like doing a bit of Java hacking to fix these issues that'd be great. :-)

Headers are only parsed once

For performance reasons, Eclipse only processes header files that have include guards once, using the compiler options for the first source file it encounters that includes that header (Eclipse bug 380511). This is responsible for most of the parse errors in the source files displayed in Eclipse. One problem with the "parse once" strategy is that the compiler options for the original source file may ifdef out sections of the header that would not be ifdef'ed out - and in fact are required by - source files in other parts of the tree.

For example, in content/svg/content/src/nsSVGEllipseElement.cpp Eclipse shows a parse error due to NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO not being defined. This define is in nsDOMClassInfoID.h, which is included via the following include chain:

content/svg/content/src/nsSVGEllipseElement.cpp
 content/svg/content/src/nsSVGPathGeometryElement.h
  content/svg/content/src/nsSVGGraphicElement.h
   content/svg/content/src/nsSVGStylableElement.h
    content/svg/content/src/nsSVGElement.h
     content/base/src/nsGenericElement.h
      obj-debug/dist/include/nsDOMClassInfoID.h

In nsDOMClassInfoID.h the NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO define is behind an |ifdef _IMPL_NS_LAYOUT|. The properties for nsSVGEllipseElement.cpp show that this define was picked up by the build option discovery and set on nsSVGEllipseElement.cpp, but somehow it's not set for nsDOMClassInfoID.h. However, if you right click on nsDOMClassInfoID.h in the Project Explorer and select "Index > Create Parser Log File", the log shows "Context" is set to "accessible/src/base/AccEvent.cpp", not "content/svg/content/src/nsSVGEllipseElement.cpp", and if you check the properties for AccEvent.cpp, indeed it is not built with the _IMPL_NS_LAYOUT define.

One way to mitigate this problem is to explicitly define defines on problem directories. For example, to solve the _IMPL_NS_LAYOUT issue described above you would use the context menu for the 'layout' directory in the Project Explorer tab to open the directory's properties. You'd select "C/C++ General > Prepocessor Include Paths, Macros etc.", and select "GNU C++" and "CDT User Settings Entries". You'd then click "Add", select "Preprocessor Macro" from the dropdown, and set Name to _IMPL_NS_LAYOUT and leave Value blank. Finally you'd click OK twice to return to the main Eclipse window, and then use the context menu for the 'layout' directory to reindex the 'layout' directory and then to "Run C/C++ Code Analysis" on it to see if the problem is fixed.

This "parse once" strategy can also cause "Unresolved inclusion" errors in headers if the first time Eclipse sees the header is while indexing a file for which it doesn't have any build output parser data. (Since it then has no explicit include paths to search.) When this happens it frequently causes knock-on errors for the files that include that header (directly or indirectly) since they too now have things missing. People who have their object directory outside their source directory need to take special note of this issue. When the object directory is inside the source directory (and not filtered out by a resource filter) then Eclipse's "Allow heuristic resolution of includes" option (enabled by default) will generally allow the included headers to be found when Eclipse processes source files that don't have any build output parser data. However, when the object directory is outside the source directory, Eclipse doesn't know about it - or the headers it contains - unless the user takes extra steps to tell it. This is the reason that the instructions in the Initial project properties section above instruct users that have their object directory outside their source directory to explicitly add {objdir}/dist/include to the project's "CDT User Setting Entries".

Fixing Eclipse bug 381601 would considerably reduce the impact of the "Unresolved inclusion" issue. (Update 2017-03-28: The option Index all header variants has been added in version 8.3.0, as explained in a comment of the mentioned bug. This option allows to have multiple definitions for the same header file, which might fix this issue.)

There are parser errors

It is expected that Eclipse will show parser errors even for a known-good copy of the Mozilla source. Parser errors/warnings are indicated by red/yellow markers on files in the Project Explorer tab, and in the gutter down the right hand side of open source files. In the case of the latter you can click on the marker to jump to the problem line and then hover over the "bug" icon to get an explanation of what's wrong.

The parser error indicators don't seem to show (reliably?) until you open a source file, then error markers will be added for that file. To force all markers to show for a directory in the Project Explorer tab, right click that directory in the Project Explorer tab and select "Run C/C++ Code Analysis". As well as adding the markers, this will give you a list of the issues in the Problems tab at the bottom of the window where you can double click to jump to the location of any given issue.

Many of the parser errors are the result of the Headers are only parsed once issue, while others are the result of Eclipse trying to do its best to process files that are not build under your configuration (e.g., files compiled only on other platforms) and that therefore have no build output parser data associated with them.

If you are trying to dig into a particular parser errors to figure out what it's about, here are a few things you can try:

  1. Select your project in the Project Explorer, then from the context menu select "Index > Search for Unresolved Includes".
  2. For problematic source files, select the file in the Project Explorer and from the context menu select "Index > Create Parser Log File".
  3. Select your project in the Project Explorer, then from the context menu select "Index > Rebuild". When the indexing is done, open the log using "Window > Show View > Other > General > Error Log" and check the summary and look for exceptions.

Searching

Free text search is not backed by a database, so it is extremely slow. Furthermore the results are not saved, so if you immediately search for the exact same text again without any changes to the source files having occurred, Eclipse will do a slow search all over again.

It is not easy to restrict searches to an arbitrary directory, which is pretty annoying given how slow free text search is. (You have to create a new working set containing that directory.)

Search history in a project is not preserved across restarts.

Duplicate searches in history - even consecutive ones - are not coalesced.

Duplicate files

Sometimes when searching for files or symbols you will be given the option between a file in the source tree, and a file of the same name under the object directory. (Some source and header files are copied to the object directory by the build process, so we end up with copies in both places.) This will happen if your object directory is inside the source directory. If you don't want to switch to using an object directory that's outside your source tree, then this is just one of those things that you'll have to live with. (If you do change the location of your object directory, then note the instructions that will then apply to you in the Initial project properties section above!) Since the indexer needs to be able to resolve header files in the object directory in order to produce good results, we can't have Eclipse ignore the object directory. But then there's no way to tell Eclipse that any given file in the object directory is actually just a copy of a given file in the source directory, and that it should always show the user the copy in the source directory while using the file in the object directory for indexing.

Building

Eclipse's support for building only in certain directories is nonexistent. It would be great if the Console tab gave you a shell prompt so that you could invoke commands to build directly from there.

Failing that, it would be nice if Eclipse could at least pass information about what files have changed to the build process, which could then decide on a faster way to do the build (e.g., "just make in layout/"). I (roc) have actually written a small change to the CDT Make builder that lets you specify that as an option, in which case Eclipse sends the names of all changed files to your build tool. The build tool is a Perl script that figures out if a faster build is possible and if so, does it.

FAQ

Here are some frequently asked questions.

Why does Eclipse need an object directory?

To provide good code assistance Eclipse needs you to have a build directory for two reasons.

First, Eclipse needs to be able to collect a usable set of defines, include paths, and preinclude files for the source files in the tree, as explained in the Code assistance section above.

Second, Eclipse CDT's indexer needs an object directory because virtually all Mozilla source files include header files (directly or indirectly) that have been copied to or generated in the object directory. Without an object directory the indexer would find that a lot of header files are missing when processing the source files, which would significantly degrade its ability to index the source and provide good code assistance.

How can I open Eclipse for multiple trees at once?

To be able to open more than one workspace at a time, you currently need to launch a separate Eclipse process for each workspace.

On Mac, create a script called something like open-my-workspace.py, give it the following contents, replacing the bold paths as appropriate, and make it executable (chmod a+x open-my-workspace.py):

#!/usr/bin/env python
import os, subprocess
eclipse_app_path = "path/to/Eclipse.app/Contents/MacOS/eclipse"
workspace_path = os.path.join(os.environ['HOME'], "HOME/relative/path/to/the/directory/of/the/workspace/you/want/to/open")
subprocess.Popen([eclipse_app_path, "-data", workspace_path])
# Uncomment the following line to automatically close the Terminal window
# that opens if you run this script by double clicking it in Finder.
#subprocess.Popen(["osascript", "-e", 'tell application "Terminal"', "-e", "close front window", "-e", "end tell"])

TODO: add instructions for Linux and Windows.

Is there a Mercurial plugin for Eclipse?

There is MercurialEclipse, but probably most Mozilla developers will just prefer to use the command line. If you think we need our own documentation on MercurialEclipse, please consider adding a separate page for that tool since this page is already pretty long.

How can I delete my Eclipse project and start over?

If you followed the recommendation above to create one workspace containing only one project for each Mozilla tree, then this is easy. (If you didn't, and you have projects for more than one source tree entangled in a workspace directory, well, you're on your own.) Simply delete the .project and .cproject files and the .settings directory (if it exists) from the root of your Mozilla tree, and then delete the workspace directory corresponding to your tree. That's it; you can now create a new Eclipse workspace and project for your tree from scratch.

Isn't there a better method of build option discovery?

Yes, but Eclipse doesn't currently support it. Instead of processing build console output, Eclipse could use something like LD_PRELOAD to load its own little library into all the processes that are invoked as part of the build process. This library could then check whether the process is a compiler instance and, if so, use the processes' current working directory and the arguments that were passed to it to reliably obtain the information it needs for each source file that is compiled. This would eliminate the requirement for non-parallelized, non-silenced builds. You could also build from Eclipse and get the benefits that that brings.

How can I run a more recent CDT version?

This can be useful if you need to get certain bug fixes, or to help with testing to make sure that new Eclipse bugs that affect its use with Mozilla don't get shipped. If you've downloaded an Eclipse Developer build then you can use Eclipse's software update mechanism to update your developer snapshot to the latest nightly for that developer branch. To do that, carry out the following steps.

From Eclipse's "Help" menu select "Install New Software...", then in the "Install" window that opens, click "Available Software Sites". In the window that opens, click "Add", and in the prompt set Name to something like "Nightly" and Location to something like "http://download.eclipse.org/tools/cd...s/juno/nightly" (change "juno" to the current developer branch). Click "OK", then "OK" again. Type "Nightly" into the "Work with" field, and select the repository that you just added. (If it doesn't appear, close the window, reopen it from the Help menu, and try again.) A "CDT Main Features" option should now have been added in the area below. Tick this (all of its sub-options should then be ticked), click "Next" twice, accept the license agreement, and then click "Finish". Eclipse should now update itself and ask you to restart.

Troubleshooting: If you get an error when trying to update, try clicking "Available Software Sites" in the "Install" window, make sure "Juno" is still unticked, that "Nightly" is ticked, highlight "Nightly", click "Reload", "OK", and then try again.

Troubleshooting

Here is a list of problems people have encountered, and suggestions for solutions.

Problem Occurred (Java heap space)

If Eclipse becomes glacially slow or hangs and then you get this error message, see the Increasing memory limits section above. If you already carried out the instructions in that section, then double check that your changes to Eclipse's memory limits actually took effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration. If they did, then maybe you need to increase the limits still further for your OS/JVM combination.

Resource is out of sync with the file system

If you get the message "Resource is out of sync with the file system", then you didn't set the "Refresh" options above in the Initial workspace preferences section. Either set those, or else refresh the project (or an individual directory/file) manually using the Refresh item from the context menu in the Project Explorer tab.

Old

Everything that follows is old content that should maybe just be deleted now?

GDB Timeouts

I don't think this old comment from 2007/2008 is an issue any more.

Out of the box, you may/will get GDB connection timeouts. This is because Eclipse is trying to push every subfolder in GDB's environment. The easiest way to resolve this issue is to remove any source entry from the debug configuration (Run->Open Debug Dialog...) in the Source tab. Doing so will unfortunately remove the binding between the binaries and the source code. To keep this feature working, you need to add a "Path Mapping" by clicking "Add..." in the Source tab. Once a "Path Mapping" is created, select "Edit..." and add an entry with these values

 Compilation path: / 
 Local file system path: /

This is the only known workaround to bind binaries to source files. It has been tested and works perfectly under Eclipse Europa (3.3.2) with Eclipse-CDT (4.0.3).

Document Tags and Contributors

 Last updated by: bunnybooboo,