Compile with mingw under window - simple writing of makefile

1. Prepare mingw.
    Assuming that mingw is installed in C:\MinGW\bin, register this path in the system environment Path.
    Copy mingw32-make.exe, and rename it make.exe
2. Create a folder MyMakeFile, which contains the files main.cpp, mylib.h, mylib.cpp, mydll.h, mydll.cpp
    as follows:
    main.cpp:
#include " mylib.h"
#include "mydll.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    cout << "hello" << endl;
    cout << " 3 + 4 = " < < add(3, 4) << endl;
    showlog("abcdef");
    mylibc cc;
    cc.log();
    dllcls cls;
    cls.show();
    system("pause");
    return 0;
}

    mylib.h:
#ifndef _MYLIB_H
#define _MYLIB_H

int add(int a, int b);
class mylibc
{
public:
    void log();
};

#endif //_MYLIB_H

    mylib.cpp:
#include "mylib.h"
#include <stdio.h>

int add(int a, int b) { return a + b; }
void mylibc::log() { printf("mylibc----log:\n"); }

    mydll.h:
#ifndef _MYDLL_H
#define _MYDLL_H

void showlog(const char *psz);
class dllcls
{
public:
    void show();
};

#endif //_MYDLL_H

    mydll.cpp:
#include "mydll.h"
#include <iostream>

using namespace std;

void showlog(const char *psz) { cout << "showlog func:" << psz << endl; }
void dllcls::show() { cout << "dllcls show func" << endl; }

3. Re-create the files makefile and compile.bat
    compile.bat in the current directory:
make
cmd

4. About the common makefile that generates .o files and links programs:
app : mylib.o mydll.o main.o
    g++ -o app mylib.o mydll.o main.o

mylib.o : mylib.cpp mylib.h
    g++ -c mylib.cpp

mydll.o : mydll.cpp mydll.h
    g++ -c mydll.cpp

main.o : main.cpp mylib.h mydll.h
    g++ -c main.cpp
this generates app.exe

5. About generating the static library libmylib.a and using the static library writing method:
app2 : libmylib.a mydll.o
    g++ -o app2 main.cpp -L. -lmylib mydll.o

libmylib.a : mylib.o
    ar -r libmylib.a mylib.o

mylib.o : mylib.cpp mylib.h
    g++ -c mylib.cpp

mydll.o : mydll.cpp mylib.h
    g++ -c mydll.cpp
This will generate the static library libmylib.a and link it to app2.exe, where -L is the static library directory, -lmylib means link libmylib.a

6. About the writing method of generating mydll.so and using the dynamic library:
app3 : libmylib.a mydll.so
    g++ -o app3 main.cpp libmylib.a mydll.so

libmylib.a : mylib.o
    ar -r libmylib.a mylib.o

mylib.o : mylib.cpp mylib.h
    g++ -c mylib.cpp

mydll.so : mydll.cpp
    g++ mydll.cpp -fpic -shared -o mydll.so
This will generate the dynamic library mydll.so and generate app3.exe

7. Postscript:
    For more information about makefiles, please refer to "Write Makefiles with Me" written by Brother Chen Hao
    URL: http://blog.csdn.net/haoel/article/details/2886/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325436142&siteId=291194637