Skip to content

Instantly share code, notes, and snippets.

@madars
Last active September 18, 2015 06:12
Show Gist options
  • Save madars/3dda3c0727574038e6f5 to your computer and use it in GitHub Desktop.
Save madars/3dda3c0727574038e6f5 to your computer and use it in GitHub Desktop.
ODR violation
*.o
*.so
main
#ifndef HEADER_HPP_
#define HEADER_HPP_
#include <cstdio>
template<int n>
struct widget {
static int bar;
static void print(const char *msg)
{
printf("%s %d\n", msg, bar);
}
};
template<int n>
int widget<n>::bar;
#endif // HEADER_HPP_
#include "libobj.hpp"
void init_libmy()
{
libmy_widget::bar = 123;
libmy_widget::print("from init_libmy");
}
#ifndef LIBOBJ_HPP_
#define LIBOBJ_HPP_
#include "header.hpp"
typedef widget<123> libmy_widget;
void init_libmy();
#endif // LIBOBJ_HPP_
#include "header.hpp"
#include "libobj.hpp"
int main()
{
widget<123>::bar = 456;
widget<123>::print("from main"); // should be 456
init_libmy(); // should be 123
widget<123>::print("from main"); // is this guaranteed to output 123?
}
#!/bin/sh
set -x -e
rm -rf libobj.o main.o libobj.so main
g++ -fPIC -c -o libobj.o libobj.cpp
g++ -o libmy.so libobj.o -shared -fPIC
g++ -o main.o -c main.cpp
g++ -o main main.o -lmy -L . -Wl,-rpath .
./main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment