Error while trying to use structs in C ++

I am trying to figure out how to use structs like lists in C ++. I came up with a piece of code that, for my understanding, shouldn't lead to any errors, but it happened ..

My code:

struct item {
int data;
struct item *next;
};

struct item *begin = NULL;

void add(int x) {
    struct item *a = new struct item();
    a->data = x;
    a->next = begin;
    begin = a;
}

int main() {

    add(2);
    printf("%d\n", begin->data);

    return 0;
}

      

and this gives me the following:

Undefined symbols for architecture x86_64:
"operator new(unsigned long)", referenced from:
  add(int) in structtest-f49486.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

      

I am using GCC inside my mac terminal to run my code. I haven't seen this before. I found that there is no error when I delete the line

struct item *a = new struct item();

      

Can anyone tell me what is wrong here?

Thank,

Merijn

+3


source to share


1 answer


Use g++

not gcc

. It looks like it is trying to link your C ++ code as C code.

GCC is so weird. When you use g++

to link it, it silently adds C ++ support libraries such as the one that defines the default operator new

.

And yes, he "forgets" that he just compiled the code as C ++. Don't ask me why.




Regarding clang

and gcc

, here's what I see on my Mac:

$ gcc --version
gcc (MacPorts gcc48 4.8.4_0) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ type -a gcc
gcc is /opt/local/bin/gcc
gcc is /usr/bin/gcc
$ /usr/bin/gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
$ ls -lF /usr/bin/gcc
-rwxr-xr-x  1 root  wheel  14160 Sep 29  2014 /usr/bin/gcc*
$ ls -lF /usr/bin/g++
-rwxr-xr-x  1 root  wheel  14160 Sep 29  2014 /usr/bin/g++*
$ file /usr/bin/gcc
/usr/bin/gcc: Mach-O 64-bit executable x86_64
$ file /usr/bin/g++
/usr/bin/g++: Mach-O 64-bit executable x86_64
$ diff /usr/bin/g++ /usr/bin/gcc
Binary files /usr/bin/g++ and /usr/bin/gcc differ

      

Note that I have MacPorts installed, with real GCC 4.8 installed and configured to "replace" Apple "gcc". BTW, Apple is gcc

not a symbolic link.

+9


source







All Articles