我正在尝试在C中实现某种“类”。
我的代码目前包含以下3个文件:
SampleHeader.h:
#ifndef SAMPLE_CLASS_H
#define SAMPLE_CLASS_H
struct Sample {
int i, j;
};
extern const struct SampleClass {
struct Sample (*new)(int i, int j);
} Sample;
#endif
SampleClass.c:
#include <stdio.h>
#include "SampleHeader.h"
static struct Sample new (int i, int j) {
return (struct Sample) {
.i = i, .j = j
};
const struct SampleClass Sample = {
.new = &new
};
}
test.c的:
#include <stdio.h>
#include "SampleHeader.h"
int main (void) {
struct Sample classInC = Sample.new(3, -4);
return 0;
}
无耻地从[删除]中撕掉。
问题是在编译时(gcc -o app test.c SampleClass.c
)它失败了:
In function 'main':
undefined reference to 'Sample'
有谁知道我做错了什么以及如何解决这个问题?
提前致谢。
答案 0 :(得分:2)
您没有按照链接中的模式进行操作。
static struct Sample new (int i, int j) {
return (struct Sample) {
.i = i, .j = j
};
const struct SampleClass Sample = {
.new = &new
};
}
应该是
static struct Sample new (int i, int j) {
return (struct Sample) {
.i = i, .j = j
};
}
const struct SampleClass Sample = {
.new = &new
};
答案 1 :(得分:0)
您的SampleClass.c可能包含:
static struct Sample new (int i, int j) {
return (struct Sample) {
.i = i, .j = j
};
}
const struct SampleClass Sample = {
.new = &new
};