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

标签 c++ struct

我正在尝试了解如何在 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("%d\n", 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 代码。

GCC 像这样很奇怪。当您使用 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”。顺便说一句,Apple 的 gcc 不是符号链接(symbolic link)。

关于c++ - 尝试在 C++ 中使用结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877527/

相关文章:

c++ - 来自 g++ -fanalyzer 的 std::vector 空指针取消引用

c++ - 重定向标准 I/O : freopen + stdin/stdout vs open + dup2

c - 声明链表节点

C 代码在 Linux Debian 中编译失败

C语言: memory allocation of a structure of two char* pointers

c - 我是否在我的结构指针上正确地调用了 free() ?

c++ - U0.8、U4.8、U12.8、S0.4、S4.4、S12.4、U8.8等定点表示法究竟是什么意思?

c++ - boost::asio::async_read_some在父线程中运行

c++ - 给定点文本 c++ 生成 GraphViz 图的图像

c - 结构体初始化时静态存储类出错