在 Windows 设备中使用 cs50 库需要帮助

问题描述 投票:0回答:1

我正在 Windows 10 设备中使用 Visual Studio Code,并且居住在互联网访问状况不佳的地区。

我已经完成了 cs50x 第一周的讲师课程。 已提取

cs50.h
cs50.c
并将它们复制到
C:\msys64\mingw64\include\
现在运行代码后,我得到
undefined reference to 'get_int'
 Id returned 1 exit status

  1. 经过一些在线解决方案后,我明白了

在源代码中,将

#include <cs50.h>
更改为
#include <cs50.c>
但我在
<cs50.h>
中没有找到任何
cs50.c source file
,而是有
"cs50.h"

  1. 我无法理解

如何在使用 clang 编译代码时链接 cs50,方法是使用

-lcs50

c cs50 getstring
1个回答
0
投票

它不起作用,因为你没有先编译库。操作方法如下:

1.下载库文件:

从此 URL 下载最新版本的 cs50 库头 (

cs50.h
) 和源 (
cs50.c
) 文件:https://github.com/cs50/libcs50/tree/main/src。确保这两个文件放置在同一目录中。

2.编译源代码:

使用以下命令编译

cs50.c
文件(确保
cs50.h
cs50.c
位于同一目录中):

gcc -c cs50.c

此命令会在同一目录中创建一个名为

cs50.o
的已编译目标文件。

3.创建静态库:

使用

ar
(GNU Binutils) 工具创建存档静态库文件。在 Windows 中,MinGW 编译器通常默认安装
ar

ar rcs libcs50.a cs50.o

此命令创建一个名为

libcs50.a
的静态库文件。

注意: 您现在可以删除

cs50.o
文件,因为不再需要它。

4.测试库(test.c):

创建一个

test.c
文件来测试库是否正常工作:

#include <cs50.h>
#include <stdio.h>

int main()
{
    string str = get_string("What is your name?: ");
    printf("Hello, %s!\n", str);
    return 0;
}

5.组织文件结构(可选):

为了更好的组织,您可以创建特定的目录结构来管理库文件:

.
├── include
│   └── cs50.h
├── lib
│   └── libcs50.a
└── test.c

cs50.h
头文件复制到
include
目录中。 将静态库
libcs50.a
移动到
lib
目录。

6.编译测试程序:

使用以下命令编译

test.c
源代码:

gcc -I./include -L./lib test.c -o test -lcs50

标志说明:

  • -I./include
    指定包含头文件的目录(此处为
    ./include
    )。
  • -L./lib
    指定包含库的目录(此处为
    ./lib
    )。
  • test.c
    :要编译的源代码文件。
  • -o test
    :
    将输出可执行文件名设置为
    test
  • -lcs50
    :
    将程序与静态库链接
    libcs50.a

7.执行测试程序:

编译完成后,您只需在终端中输入测试程序的名称即可运行测试程序:

./test

这将提示您输入姓名,然后将其打印回控制台。

示例输出:

What is your name?: World
Hello, World!
© www.soinside.com 2019 - 2024. All rights reserved.