#!/bin/sh -e
AR=ar
NM=nm
CC=gcc
CFLAGS=""
#use gcc-ar and gcc-nm when using -flto -fuse-linker-plugin"
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 = {42};
struct foo *const hasfoo = &foo;
_EOF
cat > main.c << _EOF
// main.c
int f(void);
int main()
{
    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
echo "************************************************************"
echo "Running with ..."
gcc --version
ld --version
echo "************************************************************"
ret=0
./a || ret=${?}
echo "Case 0: ${ret}"
echo "************************************************************"
rm -f a.a a
${CC} ${CFLAGS} -o a main.o a.o b.o
echo "************************************************************"
ret=0
./a || ret=${?}
echo "Case 1: ${ret}"
echo "************************************************************"
rm -f a.a a
${AR} r a.a a.o
${NM} a.a
${CC} ${CFLAGS} -o a main.o a.a
echo "************************************************************"
ret=0
./a || ret=${?}
echo "Case 2: ${ret}"
echo "************************************************************"
rm -f a.a a
${AR} r a.a a.o b.o
${NM} a.a
${CC} ${CFLAGS} -o a main.o a.a
echo "************************************************************"
ret=0
./a || ret=${?}
echo "Case 3: ${ret}"
echo "************************************************************"
rm -f a.c b.c main.c a.o b.o main.o a.a a
