Using a method defined in another .dll

Development environmnet: Windows 10, Visual Studio 2017.

I have the following methods defined in api.h and implemented in api.cpp then compiled into api.dll. Compilation also produced api.lib.

extern "C" int validate( int v_mode, char * data, int data_length );

I have created another different project. In that project I included api.h, and then from project settings, I added api.lib into additional libraries to link with as well as I set the additional libraries directory.

This project is super simple console application with which I will test the previously mentioned validate method.

#include "api.h"
int main() {
    char data[] ={1,2,3};
    validate(ValidationModes::Video,data,3);
}

I get the following error:

error LNK2019: unresolved external symbol validate referenced in function main

Well as the compiler is telling it is linking error. After a bit of searching, I added __declspec(dllexport) to my validate method.

extern "C" __declspec(dllexport) int validate( int v_mode, char * data, int data_length );

Then I could compile and run without any problems. My question is the following:

For any method, class, variable etc, which exists in A.dll, if I try to access those methods, classes, variables etc. from an outside source such as my test application, do I have to set them as __declspec?

I am fairly new to c++ development in Windows environment. I do not remember ever doing something similar to this when I was using g++. Thanks in advance.

Upvotes: 0

Views: 56

Answers (1)

user3132457
user3132457

Reputation: 1019

Yes, if you wanna use those "names" (function, variable, class, etc.) outside the DLL, you have to "export" them. Note that you only need to do that on Windows (where symbols are not exported from DLL by default). On Linux it's the opposite - all symbols are exported and you'd need to hide whatever you don't want to be exported.

Upvotes: 3

Related Questions