vendredi 19 février 2021

Linking my Dynamic Link Library to my CPP executable

I'm using CLion with cmake.

I want to link my dll to my c++ project in cmakelists.txt but I don't know how to do that.

I have searched a lot but I didn't find any solution.


  1. I have published a dll by visual studio in c++ which I want to link to my cmake project.
    • the project name and output name is Benchmark -> Benchmark.dll

here is the code: module.hpp

#pragma once
#ifdef CFAMILY_EXPORTS
#define CFAMILY_API __declspec(dllexport)
#else
#define CFAMILY_API __declspec(dllimport)
#endif

typedef std::chrono::steady_clock::time_point tpoint;
typedef std::chrono::seconds secs;
typedef std::chrono::milliseconds millis;
typedef std::chrono::microseconds micros;
typedef std::chrono::nanoseconds nanos;
using std::chrono::duration_cast;
const auto tnow = std::chrono::high_resolution_clock::now;

extern "C" {
    CFAMILY_API void ResetTimer();
    CFAMILY_API void StartTimer();
    CFAMILY_API void FinishTimer();
    CFAMILY_API long long GetTimer();
    CFAMILY_API long long GetTimerMillis();
    CFAMILY_API long long GetTimerMicros();
    CFAMILY_API long long GetTimerNanos();
}

module.cpp

#include "pch.h"
#include "module.hpp"

static auto start_time = tpoint();
static auto end_time = tpoint();

void ResetTimer()
{
    start_time = tpoint();
    end_time = tpoint();
}

void StartTimer() { start_time = tnow(); }

void FinishTimer() { end_time = tnow(); }

long long GetTimer() { return duration_cast<secs>(end_time - start_time).count(); }

long long GetTimerMillis() { return duration_cast<millis>(end_time - start_time).count(); }

long long GetTimerMicros() { return duration_cast<micros>(end_time - start_time).count(); }

long long GetTimerNanos() { return duration_cast<nanos>(end_time - start_time).count(); }
  1. then in my project in clion I want to use it:main.cpp
#include <iostream>
// include my benchmark.dll here and use its methods

int main() {
    // StartTimer(); in dll
    for (int i = 0; i < 1000000; i++) continue;
    // FinishTimer(); in dll
    // cout << GetTimerNanos() << endl;

    return 0;
}

cmakelists.txt

cmake_minimum_required(VERSION 3.17)
project(SpeedTest)

set(CMAKE_CXX_STANDARD 20)

add_executable(SpeedTest main.cpp)

find_library(${PROJECT_NAME}
    NAMES Benchmark
    HINTS "D:\\VS Projects\\BenchmarkLibrary\\C-Family\\Release-output\\x64")

Aucun commentaire:

Enregistrer un commentaire