尝试在C++中使用结构时出错

Error trying to use structs in C++

本文关键字:结构 出错 C++      更新时间:2023-10-16

我试图理解如何在C++中使用结构作为列表。我想出了一段代码,据我所知,它不应该导致任何错误,但它确实如此。

我的代码是这样的:

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("%dn", begin->data);
    return 0;
}

它给了我这个:

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)

我在Mac终端中使用GCC来运行我的代码。我以前从未见过这种类型的错误。我发现删除该行时不存在错误

struct item *a = new struct item();

谁能告诉我这里出了什么问题?

谢谢

梅里恩

使用g++而不是gcc 。看起来它正在尝试将您的C++代码链接为 C 代码。

海湾合作委员会像这样很奇怪。当您使用 g++ 链接时,它会以静默方式添加C++支持库,例如定义默认operator new库的库。

是的,它"忘记"了它只是将代码编译为C++。不要问我为什么。


关于clanggcc,这是我在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

请注意,我已经安装了MacPorts,通过它安装了真正的GCC 4.8,并已将其配置为"替换"Apple的"gcc"。顺便说一句,苹果的gcc不是符号链接。