Force a linker to fail with a multiple definition error, even if including --whole-archive

Viewed 1043

This example consists of multiple files:

// baz.cxx
int wat = 0;
int counter = ++wat;
// foo.cxx (empty)
// bar.cxx (empty)
// main.cxx
#include <iostream>
extern int wat;
int main() {
    std::cout << wat << '\n';
}
// makefile
run : main.cxx foo.so bar.so
    g++ -std=c++11 $^ -o $@

baz.a : baz.cxx
    g++ -std=c++11 -c $^ -o baz.o -fPIC
    ar rcs $@ baz.o

%.so : %.cxx baz.a
    g++ -std=c++11 $< -Wl,--whole-archive baz.a -Wl,--no-whole-archive -o $@ -shared -fPIC

As-is, if you just run make && LD_LIBRARY_PATH=. ./run, everything with compile, build, link, run and output 2. This is because both foo.so and bar.so provide wat, and the initialization for counter is run twice.

Is there a way to somehow force run to fail to link with a multiple definition error in this case, while still ensuring that both foo.so and bar.so have a definition for wat?

2 Answers
Related