我正在使用 ubuntu 16.04 当我尝试使用以下命令编译程序时
g++ -g main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
这是我的 g++ 版本
g++ --version
Run Code Online (Sandbox Code Playgroud)
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Run Code Online (Sandbox Code Playgroud)
我收到这个编译错误
main.cpp:8: undefined reference to `Helper::IsStringNumeric(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
主要.cpp:
#include "Helper.h"
#include <iostream>
#include <vector>
int main()
{
std::cout << Helper::IsStringNumeric("200");
}
Run Code Online (Sandbox Code Playgroud)
助手.h
#ifndef HELPER_H
#define HELPER_H
#include <vector>
#include <string>
class Helper
{
private:
/* data */
public:
static bool IsStringNumeric(const std::string &str);
};
#endif
Run Code Online (Sandbox Code Playgroud)
助手.cpp
#include "Helper.h"
#include <string>
#include <algorithm>
bool Helper::IsStringNumeric(const std::string &str)
{
std::string::const_iterator iterator = str.begin();
while (iterator != str.end() && std::isdigit(*iterator))
{
++iterator;
}
return !str.empty() && iterator == str.end();
}
Run Code Online (Sandbox Code Playgroud)
我的 cpp 和头文件看起来是正确的,所以我不确定为什么会出现错误
添加#include "Helper.h"到 yourmain.cpp使得的声明Helper::IsStringNumeric对编译器可见,但是您仍然需要编译Helper.cpp为目标代码,以便在链接程序时使的定义可用。Helper::IsStringNumericmain
您可以将每个翻译单元编译为目标代码文件,然后链接它们:
g++ -g -o main.o -c main.cpp
g++ -g -o Helper.o -c Helper.cpp
g++ main.o Helper.o -o main
Run Code Online (Sandbox Code Playgroud)
或者(对于简单的程序)一步完成所有操作
g++ -g main.cpp Helper.cpp -o main
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11756 次 |
| 最近记录: |