Dynamic link library does not generate a .lib file when compiled (Visual Studio C++ Express)

StackOverflow https://stackoverflow.com/questions/5019809

  •  14-11-2019
  •  | 
  •  

Pergunta

As part of learning C++, I wrote a simple class library + application that references it. Everything builds, except the class library does not generate a .lib file, which results in the application throwing a "LINK : fatal error LNK1104: cannot open file". This seems very reasonable; obviously, if a necessary file isn't there, there's an error and it's fatal. (Side note: I don't have a book yet)

So, I went looking for reasons a .lib file might not be generated. My search-fu, by the way, is rather weak. All I did find was that, if the library did not have any __declspec(dllexport) tags, it would not export a .lib.

I shall now post the header and .cpp contents of the class library (A simple "Console" class with one "Write(std::string)" method).

Header:

// Extensions.h

#pragma once

#include "stdafx.h"

namespace Extensions {

    __declspec(dllexport) class Console
    {
    public:
        __declspec(dllexport) static void Write(std::string text);
    };
}

I am unsure whether I need to tag the function when I've tagged the class, but I can check that when it works.

And the .cpp file:

// This is the main DLL file.

#include "stdafx.h"

// #include "Console.h"

namespace Extensions {

    void Console::Write(std::string text)
    {
        std::cout << text.c_str();
    }
}

I've checked and it is set to generate a dynamic link library.

Thanks.

Foi útil?

Solução

Here is some sample code that demonstrates how to correctly export a class. Pay attention to the CONSOLETEST_EXPORT macro. This is the missing part of your solution. You need to define this macro in your DLL project, and leave it undefined in the projects that reference this dll.

// MAIN.CPP - TestApplication

#include <iostream>
#include "ConsoleTest.h"

int main(int argc, char** argv)
{
    std::cout << "Hello World" << std::endl;

    ConsoleTest test;

    test.Write();
    ConsoleTest::StaticWrite();

    system("pause");
}


// ConsoleTest.h - TestDll 

#include <iostream>

#ifdef CONSOLETEST_EXPORT
    #define CONSOLETEST_API __declspec(dllexport)
#else
    #define CONSOLETEST_API __declspec(dllimport)
#endif

class CONSOLETEST_API ConsoleTest
{
public:
    ConsoleTest();
    ~ConsoleTest();
    void Write();
    static void StaticWrite();
};


// ConsoleTest.cpp - TestDll

#include "ConsoleTest.h"

ConsoleTest::ConsoleTest()
{
}

ConsoleTest::~ConsoleTest()
{
}

void ConsoleTest::Write()
{
    std::cout << "Instance Write" << std::endl;
}

void ConsoleTest::StaticWrite()
{
    std::cout << "Static Write" << std::endl;
}

Check out this article on codeproject for more details. HowTo: Export C++ classes from a DLL

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top