Problems linking static library to c++ project wit

2019-08-27 11:20发布

问题:

Edit: ***Sorry I realize there must have been some misunderstanding when posting this question, I want to specify that I DO realize this question was asked a few times, none of the answers work for me however***

I've been trying to link a simple static library test to one of my c++ projects, but I can't seem to get it quite right. I know that this is a very widespread topic and that a lot of people have already asked a similar question, but even after reading some of the answers, I still cannot, for the love of god, figure out what I am doing wrong.

My code is very simple, first I have a .cpp source file titled "Math.cpp" that looks like this:

#include "Math.h"

int max(int a, int b) {

    return a > b ? a : b;

}
int min(int a, int b) {

    return a < b ? a : b;

}
int floor(double a) {

    return (int) a;

}
int ceil(double a) {

    return (int) a + 1;

}

..And to go with that I made a header file called "Math.h" that looks like this:

#pragma once

int max(int, int);
int min(int, int);
int floor(double);
int ceil(double);

I then compile "Math.cpp" with the following command on cmd:

g++ -c Math.cpp -o Math.o

...and then compile it into a static library like so:

ar rcs libMath.a Math.o

After all of this I make a new c++ soure file titled "Main.cpp" that looks like this:

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

int main() {

    std::cout << max(9, 8) << std::endl;
    return 0;

}

("Math.h" is in the same directory as "Main.cpp")

So finally in order to link "Main.cpp" with my static library ("libMath.a"), I use the following command in cmd:

g++ -o Main.exe Main.cpp -L. -lMath 

however, at this point, it throws the following error:

C:\Users\zalmar\AppData\Local\Temp\ccmOnvyg.o:Main.cpp:(.text+0x18): undefined reference to `max(int, int)'
collect2.exe: error: ld returned 1 exit status

... I cannot figure out why it can't find the reference to the specific function. Some people appeared to have the same problem (here for example). Their solution was to declare the Main.cpp source file before declaring the library path. However, that was not the case for me, even though I made sure I was linking the library after the Main.cpp it still came up with the same error. I would greatly appreciate it if someone could point out anything I might be doing wrong because clearly I must be doing something wrong. Otherwise it might be a problem with my MinGW compiler, maybe?

I also want to re-mention that this is just a test library and I am fully aware that it might be a bit overkill to compile an entire static library from such a simple program. I am simply trying to figure out how to link libraries to my c++ projects...