我想編譯一個非常簡單的C++代碼,並根據gcc參數的順序獲取鏈接錯誤。任何人都可以解釋這兩個命令行之間有什麼區別嗎?使用「gcc」編譯器編譯C++簡單文件
//這工作得很好
gcc -x c++ -c *.h *.cpp (first I pass *.h files then *.cpp)
gcc -lstdc++ *.o -o exe
//這給出了一個錯誤
gcc -x c++ -c *.cpp *.h (first I pass *.cpp files then *.h)
gcc -lstdc++ *.o -o exe
請問GCC護理參數序列?
實例:
//這CASE工作正常
[[email protected] ~/C++]$ ls Employee.cpp Employee.h Main.cpp [[email protected] ~/C++]$ gcc -x c++ -c *.h *.cpp [[email protected] ~/C++]$ ls Employee.cpp Employee.h Employee.o Main.cpp Main.o Makefile [[email protected] ~/C++]$ gcc -lstdc++ *.o -o exe [[email protected] ~/C++]$ ls exe Employee.cpp Employee.h Employee.o Main.cpp Main.o
//這是有問題的CASE
[[email protected] ~/C++]$ ls Employee.cpp Employee.h Main.cpp [[email protected] ~/C++]$ gcc -x c++ -c *.cpp *.h [[email protected] ~/C++]$ ls Employee.cpp Employee.h Employee.o Main.cpp Main.o [[email protected] ~/C++]$ gcc -lstdc++ *.o -o exe Main.o: In function `main': Main.cpp:(.text+0x8d): undefined reference to `Employee::Employee()' collect2: ld returned 1 exit status
Employee.h
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee();
Employee(string theName, float thePayRate);
string getName() const;
float getPayRate() const;
float pay(float hoursWorked) const;
protected:
string name;
float payRate;
};
Employee.cpp
#include "Employee.h"
Employee::Employee() {
}
Employee::Employee(string theName, float thePayRate) {
name = theName;
payRate = thePayRate;
}
string Employee::getName() const {
return name;
}
float Employee::getPayRate() const {
return payRate;
}
float Employee::pay(float hoursWorked) const {
return hoursWorked * payRate;
}
Main.cpp的
#include "Employee.h"
int main() {
Employee e;
return 0;
}
您不應該將.h文件傳遞給gcc。 – 2012-03-21 00:21:56
什麼是'錯誤'?另外,你的'* .h'文件中有什麼必須明確地將它們提供給編譯器? – 2012-03-21 00:23:38
是的,它確實關心鏈接庫的順序,儘管這完全與你的錯誤無關,但與你的問題有關 – learnvst 2012-03-21 00:24:24