登录 用户中心() [退出] 后台管理 注册
   
您的位置: 首页 >> CLQ工作室开源代码 >> 主题: Zig学习篇|zig调用c语言标准库函数[zt]     [回主站]     [分站链接]
标题
Zig学习篇|zig调用c语言标准库函数[zt]
clq
浏览(261) + 2022-10-13 14:35:56 发表 编辑

关键字:


https://zhuanlan.zhihu.com/p/459281215

Zig学习篇|zig调用c语言标准库函数
yalight
yalight

东北大学秦皇岛分校 教师

zig语言的强大功能之一是无缝调用c标准库的函数。

在c语言中,有一个getchar()函数,用来读取终端的输入字符。在zig中,调用这个函数的步骤如下:

1.创建一个zig工程

zig init-exe

2.用@cImport,@cInclude声明包含stdio.h

修改src/main.zig

const std = @import("std");

//声明#include<stdio.h>
const c = @cImport({
 // See https://github.com/ziglang/zig/issues/515
 @cDefine("_NO_CRT_STDIO_INLINE", "1");
 @cInclude("stdio.h");
 });
pub fn main() anyerror!void {
 std.log.info("get a char from stdin.", .{});
//调用c函数getchar
 var ch = c.getchar();
 std.log.info("get char:{d}\n",.{ch});
}

test "basic test" {
 try std.testing.expectEqual(10, 3 + 7);
}

2.在build.zig中加入c库

exe.linkLibC();

build.zig
const std = @import("std");

pub fn build(b: *std.build.Builder) void {
 // Standard target options allows the person running `zig build` to choose
 // what target to build for. Here we do not override the defaults, which
 // means any target is allowed, and the default is native. Other options
 // for restricting supported target set are available.
 const target = b.standardTargetOptions(.{});

 // Standard release options allow the person running `zig build` to select
 // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
 const mode = b.standardReleaseOptions();

 const exe = b.addExecutable("getc", "src/main.zig");
 exe.setTarget(target);
 exe.setBuildMode(mode);
 exe.linkLibC();
 exe.install();

 const run_cmd = exe.run();
 run_cmd.step.dependOn(b.getInstallStep());
 if (b.args) |args| {
 run_cmd.addArgs(args);
    }

 const run_step = b.step("run", "Run the app");
 run_step.dependOn(&run_cmd.step);

 const exe_tests = b.addTest("src/main.zig");
 exe_tests.setTarget(target);
 exe_tests.setBuildMode(mode);

 const test_step = b.step("test", "Run unit tests");
 test_step.dependOn(&exe_tests.step);
}

3.编译运行

zig build run

或者输入如下命令

zig run src/main.zig -lc

运行结果:

info: get a char from stdin.

a

info: get char:97

输入字符'a',得到其ascii值97.




总数:0 页次:1/0 首页 尾页  
总数:0 页次:1/0 首页 尾页  


所在合集/目录



发表评论:
文本/html模式切换 插入图片 文本/html模式切换


附件:



NEWBT官方QQ群1: 276678893
可求档连环画,漫画;询问文本处理大师等软件使用技巧;求档softhub软件下载及使用技巧.
但不可"开车",严禁国家敏感话题,不可求档涉及版权的文档软件.
验证问题说明申请入群原因即可.

Copyright © 2005-2020 clq, All Rights Reserved
版权所有
桂ICP备15002303号-1