考虑以下文件:
obj.h
#pragma once
struct obj;
int obj_size(void);
void obj_set_id(struct obj*, int);
int get_obj_id(struct obj*);obj.c
#include "obj.h"
struct obj
{
int id;
};
int obj_size(void) {
return sizeof(struct obj);
}
void obj_setid(struct obj* o, int i) {
o->id = i;
}
int obj_getid(struct obj* o) {
return o->id;
}main.c
#include <stdio.h>
#include "obj.c"
int main()
{
puts("hello world");
}事实证明,这是在C (https://en.wikipedia.org/wiki/Opaque_pointer#C)中实现封装的方法。但是,当我试图编译时,我会得到一个链接器错误。这些是Visual的抱怨:
LNK2005 _obj_getid已在obj.obj中定义
错误LNK2005 _obj_setid已在obj.obj中定义
错误LNK2005 _obj_size已在obj.obj中定义
错误LNK1169找到一个或多个经多重定义的符号
如果有人想知道,它将被设置为C代码。
当我尝试用clang编译它时,我会遇到以下错误:
clang-7 -pthread -lm -o main main.c obj.c
/tmp/obj-36b460.o: In function `obj_getid':
obj.c:(.text+0x30): multiple definition of `obj_getid'
/tmp/main-a2c3dc.o:main.c:(.text+0x30): first defined here
/tmp/obj-36b460.o: In function `obj_setid':
obj.c:(.text+0x10): multiple definition of `obj_setid'
/tmp/main-a2c3dc.o:main.c:(.text+0x10): first defined here
/tmp/obj-36b460.o: In function `obj_size':
obj.c:(.text+0x0): multiple definition of `obj_size'
/tmp/main-a2c3dc.o:main.c:(.text+0x0): first defined here
/tmp/main-a2c3dc.o: In function `main':
main.c:(.text+0x59): undefined reference to `obj_set_id'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
compiler exit status 1我已经尝试过extern-ing -- obj.h中的函数声明,但这也不起作用。inline-ing也是这样。
发布于 2019-10-16 18:35:31
以目前的状态回答你的问题:
您的错误是包含"obj.c“而不是"obj.h”。
#include指令起作用(简短地说),比如如果命名文件的内容取代了指令。
如果您编译了"main.c“和"obj.c”,则需要将"obj.c“中的所有内容两次提供给链接器。这就是为什么它给了你错误。
如果你有新的信息,你可以编辑你的问题来更新它。
https://stackoverflow.com/questions/58414011
复制相似问题