c++编译问题;类方法

C++ compiling problem; class methods

本文关键字:类方法 问题 编译 c++      更新时间:2023-10-16

我已经开始写一个非常简单的类,各种各样的类方法似乎给我带来了问题。我希望问题出在我身上,解决办法很简单。

命令g++ -o main main.cpp给出如下输出:

/usr/bin/ld: Undefined symbols:
Lexer::ConsoleWriteTokens()
collect2: ld returned 1 exit status

main.cpp:

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

int main(){
   Lexer lexhnd = Lexer();
    std::cout << "RAWRn";
    lexhnd.ConsoleWriteTokens();
   std::cout << "nn";
return 0;
 }

lexer.h:

#ifndef __SCRIPTLEXER
#define __SCRIPTLEXER
#include <iostream>
#include <string>
#include <vector>
#define DEF_TOKEN_KEYWORD 0
struct token{
 int flag;
 std::string data;
};
class Lexer
{
public:
//  bool IsTrue();
//  bool AddLine(char * line);
    void ConsoleWriteTokens(void);
private:
std::vector<token> TOK_list;
};

#endif

lexer.cpp:

bool Lexer::IsTrue(){
return true;
};

 bool Lexer::AddLine(char * line){
token cool;
cool.data = line;
TOK_list.push_back(cool);
string = line;
return true;
};
void Lexer::ConsoleWriteTokens(void){
for (int i = 0; i < TOK_list.size(); i++){
    std::cout << "TOKEN! " << i;
}
return 0;
};

我在xcode中使用g++ . btw.

事先非常感谢你,我已经研究这个问题好几个小时了。

编辑:

g++ -o main lexer.h main.cpp
or
g++ -o main lexer.cpp main.cpp
or
g++ -o main main.cpp lexer.cpp

也不工作。-Hyperzap

您没有编译lexer.cpp代码。

g++ -o main main.cpp lexer.cpp

作为编译命令。

PROBLEMS IN THE lexer.cpp

您可能希望在lexer.cpp文件

中包含lexer头文件
#include "lexer.h"

同样,你也不想从void函数返回一个整数。

void Lexer::ConsoleWriteTokens(void){
  for (int i = 0; i < TOK_list.size(); i++){
    std::cout << "TOKEN! " << i;
  }
  //This function is void - it shouldn't return something
  //return 0;
};

最后,这个函数有一些问题

bool Lexer::AddLine(char * line){
  token cool;
  cool.data = line;
  TOK_list.push_back(cool);
  //what is this next line trying to achieve?  
  //string = line;
  return true;
};

我不知道你想用我注释掉的那行来达到什么目的,它似乎没有做任何事情,字符串没有定义(你的意思是std::string mystring = line;)

最后,不要忘记取消在lexer.cpp中定义的lexer.h中声明的函数的注释。

在命令行中包含所有.cpp文件,如下所示:

g++ -o main main.cpp lexer.cpp

当您的项目增长时,以某种自动方式管理您的项目是明智的:Makefiles, ant或一些ide集成的项目文件。

g++ -o main main.cpp lexer.cpp应该可以做到。然而,我建议制作makefile文件。当有大量文件时,它们会派上用场。我还建议在编译中添加一些优化,如-O3或-O2 (O是字母O而不是零数字!)。执行速度的差异非常明显。另外,如果你打算从你的文件中创建库,为什么不使用——shared选项来创建一个喜欢的库呢?我发现创建共享库非常有用。