您好,我是编程界的新手,我正在尝试在线学习哈佛的 CS50 类(class)。
在制作我的“Hello World”程序时,我下载了“cs50.h”来定义 GetString
和 string
(至少我认为是这样)。所以这是我写的代码:
文件.c:
#include "cs50.h"
#include <stdio.h>
int main(int argc, string argv[])
{
string name;
printf("Enter your name: ");
name = GetString();
printf("Hello, %s\n", name);
}
但是,每当我尝试制作文件
时,都会发生这种情况:
cc file.c -o file
Undefined symbols for architecture x86_64:
"_GetString", referenced from:
_main in file-JvqYUC.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [file] Error 1
如果有帮助,这里是 cs50.h 文件的链接:http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.h
我想知道为什么会出现此错误以及如何修复它。请帮忙。
最佳答案
您似乎忘记了从 http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.c 下载并链接到项目 cs50.c 文件
*.h 通常只包含声明。 *.c(对于 C)和 *.cpp(对于 C++)包含实现。
这个类有GetSting函数实现:
string GetString(void)
{
// growable buffer for chars
string buffer = NULL;
// capacity of buffer
unsigned int capacity = 0;
// number of chars actually in buffer
unsigned int n = 0;
// character read or EOF
int c;
// iteratively get chars from standard input
while ((c = fgetc(stdin)) != '\n' && c != EOF)
{
// grow buffer if necessary
if (n + 1 > capacity)
{
// determine new capacity: start at 32 then double
if (capacity == 0)
capacity = 32;
else if (capacity <= (UINT_MAX / 2))
capacity *= 2;
else
{
free(buffer);
return NULL;
}
// extend buffer's capacity
string temp = realloc(buffer, capacity * sizeof(char));
if (temp == NULL)
{
free(buffer);
return NULL;
}
buffer = temp;
}
// append current character to buffer
buffer[n++] = c;
}
// return NULL if user provided no input
if (n == 0 && c == EOF)
return NULL;
// minimize buffer
string minimal = malloc((n + 1) * sizeof(char));
strncpy(minimal, buffer, n);
free(buffer);
// terminate string
minimal[n] = '\0';
// return string
return minimal;
}
关于C - cs50.h GetString 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052468/