#!/bin/sh -e
LOADER=""
CC="gcc"
AR="ar"
NM="nm"
FLIST="a.c b.c main.c a.o b.o main.o a.a a"
cd /tmp
if [ "$(ls -l ${FLIST} 2> /dev/null | wc -l)" != "0" ] ; then
    echo "Sorry one of these files exists ${FLIST} and I would like to overwrite them"
    exit 1
fi
cat > a.c << _EOF
// a.c
struct foo {int i;};
static struct foo *const dummy = 0;
extern struct foo *const hasfoo __attribute__((weak, alias("dummy")));
int f(void)
{
    return hasfoo ? hasfoo->i : 0;
}
_EOF
cat > b.c << _EOF
// b.c
struct foo {int i;};
static struct foo foo = {.i = 42};
struct foo *const hasfoo = &foo;
void g()
{
}
_EOF
cat > main.c << _EOF
// main.c
int f(void);
void g();
int main()
{
    g();
    return f();
}
_EOF
${CC} ${CFLAGS} -c a.c
${CC} ${CFLAGS} -c b.c
${CC} ${CFLAGS} -c main.c
${CC} ${CFLAGS} -o a main.o a.o b.o
echo "************************************************************"
echo -n "Running with ..."
${CC} --version
${AR} r a.a a.o b.o
${NM} a.a
${CC} ${CFLAGS} -o a main.o a.a
ret=0; ${LOADER} ./a || ret=${?}
echo "Expecting 42, got ${ret}."
echo "************************************************************"
rm -f ${FLIST}
