C/C++编程:libssh2学习(win10 + qt_creator+ qmake + vcpkg)
vcpkg
vcpkg - 一个用于管理 C 和 C++ 库的工具,支持在 Windows、Linux 和 macOS 上安装和集成各种库。
项目地址:https://gitcode.com/gh_mirrors/vc/vcpkg
·
vcpkg安装libssh2
2、安装libssh2
vcpkg install libssh2:x64-windows
测试
1、qtcreator中创建一个工程






创建的工程如下:

2、修改ssl2_test.pro。 在最下面添加:
INCLUDEPATH += C:\Users\oceanstar\vcpkg\win\vcpkg\installed\x64-windows\include
LIBS += C:\Users\oceanstar\vcpkg\win\vcpkg\installed\x64-windows\lib\libssh2.lib
3、main.cpp中
#include <QCoreApplication>
#include <libssh2.h>
#include <libssh2_sftp.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
if (!libssh2_version(LIBSSH2_VERSION_NUM)) {
fprintf (stderr, "Runtime libssh2 version too old!");
exit(1);
}
printf("libssh2 version: %s", libssh2_version(0) );
return a.exec();
}
4、运行

结果报错:code -1073741515

原因:缺失dll
解决:将vcpkg\installed\x64-windows\bin\libssh2.dll复制到qt的debug目录下

重新运行,效果如下

封装SshClient
1、创建一个类SshClient


封装1:libssh初始化与析构
sshclient.h
#ifndef SSHCLIENT_H
#define SSHCLIENT_H
#include <QLoggingCategory>
#include <QObject>
#include <libssh2.h>
#include <libssh2_sftp.h>
Q_DECLARE_LOGGING_CATEGORY(sshclient)
class SshClient : public QObject
{
Q_OBJECT
static int s_nbInstance;
QString m_name;
public:
explicit SshClient(const QString &name = "noname",QObject *parent = nullptr);
virtual ~SshClient();
QString getName() const;
void setName(const QString &name);
signals:
};
#endif // SSHCLIENT_H
sshclient.cpp
#include "sshclient.h"
Q_LOGGING_CATEGORY(sshclient, "ssh.client", QtDebugMsg)
int SshClient::s_nbInstance = 0;
SshClient::SshClient(const QString &name, QObject *parent) : QObject(parent), m_name(name)
{
if(s_nbInstance == 0)
{
qCDebug(sshclient) << "[" << __FILE__ << ","<<__FUNCTION__ << "(" << __LINE__ << ")]" << m_name << ": libssh2_init()";
Q_ASSERT(libssh2_init(0) == 0);
}
++s_nbInstance;
qCDebug(sshclient) << "[" << __FILE__ << ","<<__FUNCTION__ << "(" << __LINE__ << ")]" << m_name << ": created " << this;
}
SshClient::~SshClient()
{
qCDebug(sshclient) << "[" << __FILE__ << ","<<__FUNCTION__ << "(" << __LINE__ << ")]" << m_name << ": SshClient::~SshClient() " << this;
--s_nbInstance;
if(s_nbInstance == 0)
{
qCDebug(sshclient) << "[" << __FILE__ << ","<<__FUNCTION__ << "(" << __LINE__ << ")]" << m_name << ": libssh2_exit()";
libssh2_exit();
}
qCDebug(sshclient) << "[" << __FILE__ << ","<<__FUNCTION__ << "(" << __LINE__ << ")]" << m_name << ": destroyed";
}
QString SshClient::getName() const
{
return m_name;
}
void SshClient::setName(const QString &name)
{
m_name = name;
}
使用正常:

# this is heuristically generated, and may not be correct
find_package(Libssh2 CONFIG REQUIRED)
target_link_libraries(main PRIVATE Libssh2::libssh2)
vcpkg - 一个用于管理 C 和 C++ 库的工具,支持在 Windows、Linux 和 macOS 上安装和集成各种库。
最近提交(Master分支:4 个月前 )
cf035d99
18 小时前
96dbba1e
1 天前
更多推荐



所有评论(0)