c++ 'undefined reference to' 错误
c++ 'undefined reference to' error
我在编译 C++ 程序时遇到 "undefined reference to " 错误之一。我知道这是常见的陷阱,但到目前为止无法弄清楚我做错了什么。
这是相关代码。 Ex1Two_Sum.h:
#ifndef EX1TWO_SUM_H
#define EX1TWO_SUM_H
#include <vector>
using namespace std;
namespace ddc {
class Ex1Two_Sum
{
public:
void f();
protected:
private:
};
}
#endif
Ex1Two_Sum.cpp:
#include <vector>
#include <cstddef>
#include <iostream>
using namespace std;
namespace ddc {
class Ex1Two_Sum {
public:
void f(){
cout << "works" << endl;
}
};
}
最后,main.cpp:
#include <iostream>
#include "Ex1Two_Sum.h"
using namespace std;
using namespace ddc;
int main()
{
Ex1Two_Sum ex1;
ex1.f();
return 0;
}
我编译如下:
g++ -std=c++11 -c Ex1Two_Sum.cpp
g++ -std=c++11 -c main.cpp
g++ Ex1Two_Sum.o main.o
生成以下消息:
main.o: In function `main':
main.cpp:(.text+0x2c): undefined reference to `ddc::Ex1Two_Sum::f()'
collect2: error: ld returned 1 exit status
您的源文件使用内联函数定义重新定义了整个 class,而它只需要提供一个 non-inline 函数定义。
#include "Ex1Two_Sum.h"
void ddc::Ex1Two_Sum::f() {
std::cout << "should work\n";
}
此外,请不要将 using namespace std;
放在 header 中。不是每个人都希望全局命名空间以 potentially surprising 方式受到污染。
首先,哪一行命令抛出该错误?
其次,我想你忘了在 Ex1Two_Sum.cpp
中包含 Ex1Two_Sum.h
第三,您需要将 Ex1Two_Sum.cpp
中的 class .......
更改为:
void Ex1Two_Sum::f(){...}
我在编译 C++ 程序时遇到 "undefined reference to " 错误之一。我知道这是常见的陷阱,但到目前为止无法弄清楚我做错了什么。
这是相关代码。 Ex1Two_Sum.h:
#ifndef EX1TWO_SUM_H
#define EX1TWO_SUM_H
#include <vector>
using namespace std;
namespace ddc {
class Ex1Two_Sum
{
public:
void f();
protected:
private:
};
}
#endif
Ex1Two_Sum.cpp:
#include <vector>
#include <cstddef>
#include <iostream>
using namespace std;
namespace ddc {
class Ex1Two_Sum {
public:
void f(){
cout << "works" << endl;
}
};
}
最后,main.cpp:
#include <iostream>
#include "Ex1Two_Sum.h"
using namespace std;
using namespace ddc;
int main()
{
Ex1Two_Sum ex1;
ex1.f();
return 0;
}
我编译如下:
g++ -std=c++11 -c Ex1Two_Sum.cpp
g++ -std=c++11 -c main.cpp
g++ Ex1Two_Sum.o main.o
生成以下消息:
main.o: In function `main':
main.cpp:(.text+0x2c): undefined reference to `ddc::Ex1Two_Sum::f()'
collect2: error: ld returned 1 exit status
您的源文件使用内联函数定义重新定义了整个 class,而它只需要提供一个 non-inline 函数定义。
#include "Ex1Two_Sum.h"
void ddc::Ex1Two_Sum::f() {
std::cout << "should work\n";
}
此外,请不要将 using namespace std;
放在 header 中。不是每个人都希望全局命名空间以 potentially surprising 方式受到污染。
首先,哪一行命令抛出该错误?
其次,我想你忘了在 Ex1Two_Sum.cpp
Ex1Two_Sum.h
第三,您需要将 Ex1Two_Sum.cpp
中的 class .......
更改为:
void Ex1Two_Sum::f(){...}