Sun Studio 12: C++ User's Guide

B.2.17.1 #pragma weak name

In the form #pragma weak name, the directive makes name a weak symbol. The linker will not complain if it does not find a symbol definition for name. It also does not complain about multiple weak definitions of the symbol. The linker simply takes the first one it encounters.

If another compilation unit has a strong definition for the function or variable, name will be linked to that. If there is no strong definition for name, the linker symbol will have a value of 0.

The following directive defines ping to be a weak symbol. No error messages are generated if the linker cannot find a definition for a symbol named ping.


#pragma weak ping

#pragma weak name1 = name2

In the form #pragma weak name1 = name2, the symbol name1 becomes a weak reference to name2. If name1 is not defined elsewhere, name1 will have the value name2. If name1 is defined elsewhere, the linker uses that definition and ignores the weak reference to name2. The following directive instructs the linker to resolve any references to bar if it is defined anywhere in the program, and to foo otherwise.


#pragma weak bar = foo

In the identifier form, name2 must be declared and defined within the current compilation unit. For example:


extern void bar(int) {...}
extern void _bar(int);
#pragma weak _bar=bar

When you use the string form, the symbol does not need to be previously declared. If both _bar and bar in the following example are extern "C", the functions do not need to be declared. However, bar must be defined in the same object.


extern "C" void bar(int) {...}
#pragma weak "_bar" = "bar"

Overloading Functions

When you use the identifier form, there must be exactly one function with the specified name in scope at the pragma location. Attempting to use the identifier form of #pragma weak with an overloaded function is an error. For example:


int bar(int);
float bar(float);
#pragma weak bar        // error, ambiguous function name

To avoid the error, use the string form, as shown in the following example.


int bar(int);
float bar(float);
#pragma weak "__1cDbar6Fi_i_" // make float bar(int) weak

See the Solaris Linker and Libraries Guide for more information.