在 Linux 上面搭建C开发环境比较容易 sudo apt install build-essential libncurses5-dev gdb cmake vim
一个命令就可以搭建开发环境,在 Windows 上对于 Shell 友好的使用者可能会繁琐一些,在 Wiindows 10 之前可能大家会首选 Mingw-64 ,但随着 Windows 亲和 Linux 的产品一个一个的发布,Windows 的优越性也开始逐步浮出水面。
很多开源项目,尤其是偏底层技术栈的,比如编解码处理的 ffmpeg,网络协议 paho 等在设计之初就是原生态兼容全平台的,在发布的时候也不是通过 Windows 默认的 Visual Studio 工程的方式,而是使用了 CMake 或者 nmake 来进行工程组织,本文主要讨论一些直接调用 Windows 系统底层 API 的开源软件的开发和编译方式。
很多全平台兼容项目在 Github 集成 CI 服务时,通常会考虑三个大的操作系统 Windows、Linux、MacOS,一般 Linux 和 MacOS 可以在 Travis CI 上操作,Windows 可以在 AppVeyor 上操作。跨平台的比较成熟的工程组织方式一般都会采用 CMake,接下来我们实践一下在 Windows 中通过 Shell 方式编译这类C工程。
1. 安装 Visual Studio
下载安装 Visual Studio 本文使用 Visual Studio 2019 Community 版本,完全免费。对于只使用系统底层API的开发环境来说在安装时只需要选择 使用 C++ 的桌面开发
一项即可,这个 bundle 会包含 Windows SDK 和 MSVC 这两个我们必须的模块。
安装成功后如果想在 PowerShell 中直接使用 MSVC 需要将 INCLUDE
LIB
PATH
等环境变量加入到当前的 Shell 环境中,可以把下面的配置加入到 $PROFILE
中:
function vs_env {
$vs_path = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\Community\Common7\Tools"
Push-Location $vs_path
cmd /c "VsDevCmd.bat & set" |
ForEach-Object {
if ($_ -match "=") {
$v = $_.split("=")
Set-Item -Force -Path "Env:\$($v[0])" -Value "$($v[1])"
}
}
Pop-Location
Write-Host "`nVisual Studio Command Prompt variables set." -ForegroundColor Yellow
}
开启 PowerShell 后执行 vs_env
然后验证 cl.exe
link.exe
nmake.exe
都可以执行则安装成功。
下图不会出现在安装过程中,放在这只是为了让大家清晰 Windows SDK 都包含了哪些模块。
Visual Studio 的更新和 Office 的频率差不多,平均每两年一版,汗啊,上次使用 Visual Studio 还是 V6.0 的版本,下面这个表格为 Visual Studio 版本号与命名的对应关系
版本号 | 简称 | 全称 |
---|---|---|
VC6.0 | VS6 | Microsoft Visual Studio 6.0 |
VC7.0 | VS2002 | Microsoft Visual Studio 2002 |
VC7.1 | VS2003 | Microsoft Visual Studio 2003 |
VC8.0 | VS2005 | Microsoft Visual Studio 2005 |
VC9.0 | VS2008 | Microsoft Visual Studio 2008 |
VC10.0 | VS2010 | Microsoft Visual Studio 2010 |
VC11.0 | VS2012 | Microsoft Visual Studio 2012 |
VC12.0 | VS2013 | Microsoft Visual Studio 2013 |
VC13.0 | VS2014 | Microsoft Visual Studio 2014 |
VC14.0 | VS2015 | Microsoft Visual Studio 2015 |
VC15.0 | VS2017 | Microsoft Visual Studio 2017 |
VC16.0 | VS2019 | Microsoft Visual Studio 2019 |
VC17.0 | VS2022 | Microsoft Visual Studio 2022 |
2. 安装 Vim
在 PowerShell 中使用 Vim 已经可以媲美在 类Unix Shell 中的体验效果了。下载安装后在 PowerShell 的 $PROFILE
中 增加一个配置即可
Set-Alias vim "${Env:ProgramFiles(x86)}\Vim\vim82\vim.exe"
3. 安装 Cmake
CMake 安装比较简单,下一步到最后即可。
4. 安装 Git for Windows
Git for Windows 安装同样简单,下一步到最后即可。
5. 编译 paho.mqtt.c
Powershell 中执行:
vs_env
git_clone git@github.com:eclipse/paho.mqtt.c.git
cd paho.mqt.c
cmake -Bbuild -G "NMake Makefiles" .
cd build
nmake
nmake package
执行完成后即可看到编译完成后打包的 zip 文件。