尝试在C++中使用结构时出错
Error trying to use structs in C++
我试图理解如何在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++。不要问我为什么。
关于clang
和gcc
,这是我在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
不是符号链接。
相关文章:
- 为什么我在初始化带大括号的结构时出错?
- 尝试将指针与结构一起使用时出错
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- 尝试初始化结构内的联合时出错
- 当使用 std::CIN 输入结构时,它会出错
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 尝试将数据添加到结构内部的矢量时出错
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 尝试将结构指针传递给类时出错
- 在旧的 c++ (<c++11) 中,初始化结构会出错
- 类中私有结构的构造函数出错
- 读取结构数组时出错
- 将模板参数传递到内部结构时出错
- 创建局部结构的 std::向量时出错
- 在 C++ 中访问泛型结构的成员会出错
- 使用映射<字符串,结构>类型的映射编译头文件时出错
- 使用单元测试 (cppunit) 中另一个文件中定义的结构时出错
- 初始化作为结构成员的函数指针时出错
- C++中的初始化结构出错