C++ portability rules

Labels: , |

12. Don't put extra top-level semi-colons in code.

Non-portable example:

int
A::foo()
{
};

This is another problem that seems to show up more on C++ than C code. This problem is really a bit of a drag. That extra little semi-colon at the end of the function is ignored by most compilers, but it is not permitted by the standard and it makes some compilers report errors (in particular, gcc 3.4, and also perhaps old versions of the AIX native compiler). Don't do it.
Portable example:

int
A::foo()
{
}

13. C++ filename extension is .cpp.

This one is another plain annoying problem. What's the name of a C++ file? file.cpp, file.cc, file.C, file.cxx, file.c++, file.C++? Most compilers could care less, but some are very particular. We have not been able to find one file extension which we can use on all the platforms we have ported Mozilla code to. For no great reason, we've settled on file.cpp, probably because the first C++ code in Mozilla code was checked in with that extension. Well, it's done. The extension we use is .cpp. This extension seems to make most compilers happy, but there are some which do not like it. On those systems we have to create a wrapper for the compiler (see STRICT_CPLUSPLUS_SUFFIX in ns/config/rules.mk and ns/build/*), which actually copies the file.cpp file to another file with the correct extension, compiles the new file, then deletes it. If in porting to a new system, you have to do something like this, make sure you use the #line directive so that the compiler generates debug information relative to the original .cpp file.

14. Don't mix varargs and inlines.

Non-portable example:

class FooBar {
void va_inline(char* p, ...) {
// something
}
};

The subject says it all, varargs and inline functions do not seem to mix very well. If you must use varargs (which can cause portability problems on their own), then ensure that the vararg member function is a non-inline function.
Portable example:

// foobar.h
class FooBar {
void
va_non_inline(char* p, ...);
};

// foobar.cpp
void
FooBar::va_non_inline(char* p, ...)
{
// something
}

15. Don't use initializer lists with objects.

Non-portable example:

FooClass myFoo = {10, 20};

Some compilers won't allow this syntax for objects (HP-UX won't), actually only some will allow it. So don't do it. Again, use a wrapper function, see Don't use static constructors.
Always have a default constructor.

Always have a default constructor, even if it doesn't make sense in terms of the object structure/hierarchy. HP-UX will barf on statically initialized objects that don't have default constructors.

0 comments: