Issue
A static library declares a function with a weak symbol.
Later an application (not providing the function implementation) statically links the library but no linker error is generated.
This seems to occur with both GCC 11.4 and Clang 16.
This was discovered when asking:
No linker error when static library calls weak function with no implementation
Example:
lib_file.h:
__attribute__((weak)) int weak_func(int x, int y);
void func();
lib_file.c:
#include "lib_file.h"
void func()
{
weak_func(6, 7); // Want this to call function implemented in my app
}
app.c:
#include "./lib_file.h"
int main()
{
func();
return 0;
}
Compile and link:
gcc -c -o libfunc.o lib_file.c
ar rcs libfunc.a libfunc.o
gcc app.c -lfunc -L./
On my system gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 this generates the application executable successfully.
Running nm
on the library:
However, someone else using GCC 9.4 gets u weak_func
.
I then run my application and get a segmentation fault.
Is this correct? It feels like a silent failure.
Solution
Is this correct? It feels like a silent failure.
Yes, this is working as intended: a weak reference does not cause a link failure (and also does not cause the linker to pull a defining object from an archive library).
I then run my application and get a segmentation fault.
The usual way to call an optionally-provided function is:
void func()
{
if (&weak_func != NULL)
weak_func(6, 7); // Call weak_func if one has been provided.
}
If not providing weak_func
is an error that you want to be detected at link time, then don't declare the required function weak
.
In your other question you said:
when the library is compiled and installed, it obviously doesn't know about my application.
You appear to be under misconception that the archive library needs to know anything about your application. It doesn't -- simply remove the weak
attribute and everything will just work(TM).
More precisely, without the weak
attribute:
- your archive library will compile and install just fine
- if your app defines the function elsewhere, the link will succeed and the library will call your function
- if your app does not define the function, the link will fail
Answered By - Employed Russian Answer Checked By - Senaida (WPSolving Volunteer)