Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

C++ portability guide

What follows is a set of rules, guidelines, and tips that we have found to be useful in making C++ code portable across many machines and compilers.

None of these rules is absolute. We update the rules from time to time as C++ language features become widely implemented.

C++ portability rules

When these rules were first written down, we didn't use templates, namespaces, or inline functions of any complexity. There was also a lot of concern over interoperability between C and C++. How times change! These days, templates and inlines are some of our favorite C++ footguns. Feetgun. Whatever. C++ namespaces are now standard practice. And there's not much C code left in the codebase.

Then again, some things apparently never change.

Don't use static constructors

(You probably shouldn't be using global variables to begin with. Quite apart from the weighty software-engineering arguments against them, globals affect startup time! But sometimes we have to do ugly things.)

Non-portable example:

FooBarClass static_object(87, 92);

void
bar()
{
  if (static_object.count > 15) {
     ...
  }
}

Once upon a time, there were compiler bugs that could result in constructors not being called for global objects. Those bugs are probably long gone by now, but even with the feature working correctly, there are so many problems with correctly ordering C++ constructors that it's easier to just have an init function:

static FooBarClass* static_object;

FooBarClass*
getStaticObject()
{
  if (!static_object)
    static_object =
      new FooBarClass(87, 92);
  return static_object;
}

void
bar()
{
  if (getStaticObject()->count > 15) {
    ...
  }
}

Don't use exceptions

Gecko is a large existing codebase that uses manual error handling. We can't switch on exceptions and start throwing them because the existing code isn't exception-safe.

If you do use exceptions in some platform-specific library code or something, you must catch all exceptions there, because you can't throw the exception across XP (cross platform) code.

Don't use Run-time Type Information

This is another feature we once avoided because of uneven implementations across compilers. But we compile with RTTI disabled to this day, I guess to avoid the memory overhead.

If you need runtime typing, you can achieve a similar result by adding a classOf() virtual member function to the base class of your hierarchy and overriding that member function in each subclass. If classOf() returns a unique value for each class in the hierarchy, you'll be able to do type comparisons at runtime.

Don't use the C++ standard library (including iostream, locale, and the STL)

There are one million reasons for this. Just for starters, the C++ standard library uses exceptions and we compile with exceptions disabled. But generally it's just literally proven better to write our own, as nutty as that sounds -- our library code is smaller, it behaves the same across platforms, and it wins on correctness, efficiency, Unicode support, features, etc. Look in /mfbt.

There is one exception to this rule: it is acceptable to use placement new. You'll have to #include <new> first.

Use C++ lambdas, but with care

C++ lambdas are supported across all our compilers now.  Rejoice!  We recommend explicitly listing out the variables that you capture in the lambda, both for documentation purposes, and to double-check that you're only capturing what you expect to capture.

Use namespaces

Namespaces may be used according to the style guidelines in Mozilla Coding Style Guide.

Don't mix varargs and inlines

What? Why are you using varargs to begin with?! Stop that at once!

Don't use initializer lists with objects

Non-portable example (at least, this used to be nonportable, because HP-UX!):

SubtlePoint myPoint = {300, 400};

This is more of a style thing at this point, but why not splurge and get yourself a nice constructor?

Make header files compatible with C and C++

Non-portable example:

/*oldCheader.h*/
int existingCfunction(char*);
int anotherExistingCfunction(char*);

/* oldCfile.c */
#include "oldCheader.h"
...

// new file.cpp
extern "C" {
#include "oldCheader.h"
};
...

If you make new header files with exposed C interfaces, make the header files work correctly when they are included by both C and C++ files.

(If you need to include a C header in new C++ files, that should just work. If not, it's the C header maintainer's fault, so fix the header if you can, and if not, whatever hack you come up with will probably be fine.)

Portable example:

/* oldCheader.h*/
PR_BEGIN_EXTERN_C
int existingCfunction(char*);
int anotherExistingCfunction(char*);
PR_END_EXTERN_C

/* oldCfile.c */
#include "oldCheader.h"
...

// new file.cpp
#include "oldCheader.h"
...

There are number of reasons for doing this, other than just good style. For one thing, you are making life easier for everyone else, doing the work in one common place (the header file) instead of all the C++ files that include it. Also, by making the C header safe for C++, you document that "hey, this file is now being included in C++". That's a good thing. You also avoid a big portability nightmare that is nasty to fix...

Use override on subclass virtual member functions

The override keyword is supported in C++11 and in all our supported compilers, and it catches bugs.

Always declare a copy constructor and assignment operator

Many classes shouldn't be copied or assigned. If you're writing one of these, the way to enforce your policy is to declare a deleted copy constructor as private and not supply a definition. While you're at it, do the same for the assignment operator used for assignment of objects of the same class. Example:

class Foo {
  ...
  private:
    Foo(const Foo& x) = delete;
    Foo& operator=(const Foo& x) = delete;
};

Any code that implicitly calls the copy constructor will hit a compile-time error. That way nothing happens in the dark. When a user's code won't compile, they'll see that they were passing by value, when they meant to pass by reference (oops).

Be careful of overloaded methods with like signatures

It's best to avoid overloading methods when the type signature of the methods differs only by one "abstract" type (e.g. PR_Int32 or int32). What you will find as you move that code to different platforms, is suddenly on the Foo2000 compiler your overloaded methods will have the same type-signature.

Type scalar constants to avoid unexpected ambiguities

Non-portable code:

class FooClass {
  // having such similar signatures
  // is a bad idea in the first place.
  void doit(long);
  void doit(short);
};

void
B::foo(FooClass* xyz)
{
  xyz->doit(45);
}

Be sure to type your scalar constants, e.g., PR_INT32(10) or 10L. Otherwise, you can produce ambiguous function calls which potentially could resolve to multiple methods, particularly if you haven't followed (2) above. Not all of the compilers will flag ambiguous method calls.

Portable code:

class FooClass {
  // having such similar signatures
  // is a bad idea in the first place.
  void doit(long);
  void doit(short);
};

void
B::foo(FooClass* xyz)
{
  xyz->doit(45L);
}

Use nsCOMPtr in XPCOM code

See the nsCOMPtr User Manual for usage details.

Don't use identifiers that start with an underscore

This rule occasionally surprises people who've been hacking C++ for decades. But it comes directly from the C++ standard!

According to the C++ Standard, 17.4.3.1.2 Global Names [lib.global.names], paragraph 1:

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

Stuff that is good to do for C or C++

Avoid conditional #includes when possible

Don't write an #include inside an #ifdef if you could instead put it outside. Unconditional includes are better because they make the compilation more similar across all platforms and configurations, so you're less likely to cause stupid compiler errors on someone else's favorite platform that you never use.

Bad code example:

#ifdef MOZ_ENABLE_JPEG_FOUR_BILLION
#include <stdlib.h>   // <--- don't do this
#include "jpeg4e9.h"  // <--- only do this if the header really might not be there
#endif

Of course when you're including different system files for different machines, you don't have much choice. That's different.

Every .cpp source file should have a unique name

Every object file linked into libxul needs to have a unique name. Avoid generic names like nsModule.cpp and instead use nsPlacesModule.cpp.

Turn on warnings for your compiler, and then write warning free code

What generates a warning on one platform will generate errors on another. Turn warnings on. Write warning-free code. It's good for you. Treat warnings as errors by adding ac_add_options --enable-warnings-as-errors to your mozconfig file.

Use the same type for all bitfields in a struct or class

Some compilers (even recent ones like MSVC 2013) do not pack the bits when different bitfields are given different types. For example, the following struct might have a size of 8 bytes, even though it would fit in 1:

struct {
  char ch : 1;
  int i : 1;
};

Don't use an enum type for a bitfield

The classic example of this is using PRBool for a boolean bitfield. Don't do that. PRBool is a signed integer type, so the bitfield's value when set will be -1 instead of +1, which---I know, crazy, right? The things C++ hackers used to have to put up with...

You shouldn't be using PRBool anyway. Use bool. Bitfields of type bool are fine.

Enums are signed on some platforms (in some configurations) and unsigned on others and therefore unsuitable for writing portable code when every bit counts, even if they happen to work on your system.

Last updated April 2015

 

Document Tags and Contributors

 Contributors to this page: Jonathan_Watt, Tingyu, froydnj, cpeterson, jorendorff-moz, fscholz
 Last updated by: Jonathan_Watt,