How to create a library with Qt and use it in an application/es: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Remove non-functioning "toc" command)
m (Updating the code highlight label.)
 
Line 18: Line 18:


'''test.h'''
'''test.h'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>


Line 34: Line 34:
};
};


</code>
</syntaxhighlight>


'''test.cpp'''
'''test.cpp'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>
#include "test.h"
#include "test.h"
Line 43: Line 43:
Widget::Widget() : QWidget()
Widget::Widget() : QWidget()
{}
{}
</code>
</syntaxhighlight>


'''test.pro'''
'''test.pro'''
<code>TEMPLATE = lib
<syntaxhighlight lang="c++">TEMPLATE = lib
# Input
# Input
SOURCES ''= test.cpp
SOURCES ''= test.cpp
HEADERS''= test.h
HEADERS''= test.h
DEFINES ''= TEST</code>
DEFINES ''= TEST</syntaxhighlight>


Vea ademas la documentación en [http://doc.qt.io/qt-4.8/sharedlibrary.html Creating Shared Libraries].
Vea ademas la documentación en [http://doc.qt.io/qt-4.8/sharedlibrary.html Creating Shared Libraries].
Line 62: Line 62:


'''loadTestLib.pro'''
'''loadTestLib.pro'''
<code>
<syntaxhighlight lang="c++">
TEMPLATE = app
TEMPLATE = app
TARGET =
TARGET =
Line 70: Line 70:
# Input
# Input
SOURCES ''= main.cpp
SOURCES ''= main.cpp
</code>
</syntaxhighlight>


'''main.cpp'''
'''main.cpp'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>
#include "test.h"
#include "test.h"
Line 87: Line 87:




</code>
</syntaxhighlight>


=== Usando QLibrary para cargar la biblioteca compartida ===
=== Usando QLibrary para cargar la biblioteca compartida ===
Line 97: Line 97:


'''qlibraryLibrary.pro'''
'''qlibraryLibrary.pro'''
<code>
<syntaxhighlight lang="c++">
TEMPLATE = lib
TEMPLATE = lib
HEADERS''= widget.h
HEADERS''= widget.h
SOURCES ''= widget.cpp
SOURCES ''= widget.cpp
DEFINES''= TEST
DEFINES''= TEST
</code>
</syntaxhighlight>


'''widget.h'''
'''widget.h'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>


Line 116: Line 116:
extern "C" TEST_COMMON_DLLSPEC QWidget* createWidget1();
extern "C" TEST_COMMON_DLLSPEC QWidget* createWidget1();


</code>
</syntaxhighlight>


'''widget.cpp'''
'''widget.cpp'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>
#include "widget.h"
#include "widget.h"
Line 130: Line 130:
}
}


</code>
</syntaxhighlight>


=== Cargando la biblioteca utilizando QLibrary ===
=== Cargando la biblioteca utilizando QLibrary ===
Line 137: Line 137:
El siguiente ejemplo carga la biblioteca creada arriba y utiliza una de sus funciones para crear y mostrar un widget.
El siguiente ejemplo carga la biblioteca creada arriba y utiliza una de sus funciones para crear y mostrar un widget.


<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>


Line 160: Line 160:
  return app.exec();
  return app.exec();
}
}
</code>
</syntaxhighlight>


== Creando una biblioteca estatica ==
== Creando una biblioteca estatica ==
Line 167: Line 167:


'''test.pro'''
'''test.pro'''
<code>
<syntaxhighlight lang="c++">
TEMPLATE = lib
TEMPLATE = lib
CONFIG+= staticlib
CONFIG+= staticlib
Line 173: Line 173:
HEADERS ''= test.h
HEADERS ''= test.h
SOURCES''= test.cpp
SOURCES''= test.cpp
</code>
</syntaxhighlight>


=== Usando la biblioteca estatica en su aplicación. ===
=== Usando la biblioteca estatica en su aplicación. ===
Line 180: Line 180:


'''useStaticLib.pro'''
'''useStaticLib.pro'''
<code>
<syntaxhighlight lang="c++">
TEMPLATE = app
TEMPLATE = app
TARGET =
TARGET =
Line 189: Line 189:
LIBS+= -L../staticLibrary/debug -lstaticLibrary
LIBS+= -L../staticLibrary/debug -lstaticLibrary


</code>
</syntaxhighlight>


'''main.cpp'''
'''main.cpp'''
<code>
<syntaxhighlight lang="c++">
#include <QtGui>
#include <QtGui>
#include "test.h"
#include "test.h"
Line 204: Line 204:
  return a.exec();
  return a.exec();
}
}
</code>
</syntaxhighlight>


== Que enfoque utilizar ==
== Que enfoque utilizar ==

Latest revision as of 18:52, 22 June 2021

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

Español English


Introducción

Este tutorial ilustra diferentes enfoques para usar una biblioteca perzonalizada en tu aplicanción en Windows. La primera parte explica como crear una biblioteca compartida y como enlazarla en tu aplicación. La segunda parte es acerca de como crear y usar una biblioteca estatica.

Creando una biblioteca compartida

Cuando se crea una biblioteca compartida con la cual te gustaria enlazar tu aplicacion, debes asegurar que los simbolos que vas a usar fuera de la biblioteca son correctamente exportados cuando la biblioteca es creada. Posteriormente importada cuando estás enlazando la biblioteca. Esta puede ser hecho usando Q_DECL_EXPORT y Q_DECL_IMPORT como esta demostrado en el siguiente ejemplo:

test.h

#include <QtGui>

#if defined TEST
#define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
#else
#define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
#endif

class TEST_COMMON_DLLSPEC Widget : public QWidget
{
 Q_OBJECT
public:
 Widget();
};

test.cpp

#include <QtGui>
#include "test.h"

Widget::Widget() : QWidget()
{}

test.pro

TEMPLATE = lib
# Input
SOURCES ''= test.cpp
HEADERS''= test.h
DEFINES ''= TEST

Vea ademas la documentación en Creating Shared Libraries.

Enlazando su aplicación contra la biblioteca compartida

Con el fin de utilizar la biblioteca compartida en su aplicación, para que entonces usted pueda incluir los headers de su biblioteca y utilizar sus métodos. Compile enlazando con el arhivo .lib. En tiempo de ejecución esto carga el dll el cual tiene la implementación.

Para hacer esto, en el archivo .pro de su aplicación ustede necesita informar a la aplicación donde debe buscar los headers y la biblioteca. El INCLUDEPATH necesita apuntar al directorio donde los headers estan instalados, y la variable LIBS necesita apuntar al directorio del archivo .lib. Ademas usted necesita asegurar que el .dll es encontrado colocando en el directorio de la aplicación o en la variable global PATH.

Por ejemplo:

loadTestLib.pro

TEMPLATE = app
TARGET =
DEPENDPATH''= . ../testLib
INCLUDEPATH ''= ../testLib
LIBS''= -L../testLib/debug -ltestLib
# Input
SOURCES ''= main.cpp

main.cpp

#include <QtGui>
#include "test.h"

int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 Widget w;
 w.resize(100,100);
 w.show();
 return a.exec();
}

Usando QLibrary para cargar la biblioteca compartida

QLibrary puede ser usado para cargar bibliotecas compartidas en tiempo de ejecución. En este caso usted solo necesitara tener accesi al .dll, acceso a los headers y el archivo .lib no es necesario.

El siguinte ejemplo muestra como configurar una biblioteca para utilizarla con QLibrary. Para que los nombres de las funciones puedan ser resueltos, los mismos deben ser como funciones de C (por ejemplo, sin el name mangling) de la biblioteca. Esto significa que las funciones deben estar dentro de un bloque extern "C" si la biblioteca es compilada con un compilador de C.

Desde que estamos haciendo esto en Windows, tambien debenmos exportar la funcion del DLL utilizando Q_DECL_EXPORT y Q_DECL_IMPORT

qlibraryLibrary.pro

TEMPLATE = lib
HEADERS''= widget.h
SOURCES ''= widget.cpp
DEFINES''= TEST

widget.h

#include <QtGui>

#if defined TEST
#define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
#else
#define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
#endif

extern "C" TEST_COMMON_DLLSPEC QWidget* createWidget1();

widget.cpp

#include <QtGui>
#include "widget.h"

QWidget* createWidget1()
{
 QWidget '''wid = new QWidget();
 wid->resize(100,100);
 return wid;
}

Cargando la biblioteca utilizando QLibrary

Para cargar la biblioteca utilizando QLibrary, usted simplemente debe pasar el .dll al constructor de QLibrary. Asegurese que el .dll esta disponible en el directorio de la aplicación o dentro de la variable global PATH. Para utilizar estas funciones de la biblioteca en su aplicación, usted necesita encontrarlas utilizando QLibrary::resolve().

El siguiente ejemplo carga la biblioteca creada arriba y utiliza una de sus funciones para crear y mostrar un widget.

#include <QtGui>

int main(int argc, charargv)
{
 QApplication app(argc, argv);
 QLibrary library("qlibraryLibrary.dll");
 if (!library.load())
 qDebug() << library.errorString();
 if (library.load())
 qDebug() << "library loaded";

 typedef QWidget'''('''CreateWidgetFunction)(void);
 CreateWidgetFunction cwf = (CreateWidgetFunction)library.resolve("createWidget1");
 if (cwf) {
 QWidget''' wid = cwf();
 if (wid)
 wid->show();
 } else {
 qDebug() << "Could not show widget from the loaded library";
 }
 return app.exec();
}

Creando una biblioteca estatica

Al crear una biblioteca estatica usted debe especificar la opción staticlib al CONFIG en el archivo .pro. En contraste al ejemplo de la biblioteca compartida, usted no necesita configurar nada especial para exportar e importar simbolos en su archivo .h, ya que la biblioteca sera construida dentro de la aplicación, por ejemplo:

test.pro

TEMPLATE = lib
CONFIG+= staticlib
# Input
HEADERS ''= test.h
SOURCES''= test.cpp

Usando la biblioteca estatica en su aplicación.

De manera similar a lo que hicimos para cargar la biblioteca compartida, ahora debes configurar el INCLUDEPATH para que apunte al directorio donde se encuentran los headers y la variable LIBS que apunte al arhivo .lib, por ejemplo:

useStaticLib.pro

TEMPLATE = app
TARGET =
CONFIG+= console
# Input
SOURCES ''= main.cpp
INCLUDEPATH''= ../staticLibrary
LIBS+= -L../staticLibrary/debug -lstaticLibrary

main.cpp

#include <QtGui>
#include "test.h"

int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 Widget w;
 w.resize(100,100);
 w.show();
 return a.exec();
}

Que enfoque utilizar

El enfoque a elegir depende de tus necesidades. Cuando se crea una biblioteca compartida, usted necesita desplegarlas con su aplicación. El lado positivo es que las aplicacións enlazadas a bibliotecas compartidas son mas pequeñas. Cuando utilizar QLibrary para cargar el .dll o un enlace normal, depende de cuando usted tiene acceso a los headers y los arhivos .lib, si usted no tiene acceso a ellos, entonces QLibrary es una alternativa.

Enlace estatico resulta en un ejecutable independiente. La ventaja es que usted solo necesita tener unos pocos archivos para desplegar. La desventaja es que los ejecutables son grandes. Mire el Deployment documentation para tener mas detalles sobre versiones compartidas y estaticas.