访问头文件中定义的命名空间中的元素

Accessing elements in namespace defined in header file

我正在尝试访问头文件中命名空间中定义的变量和函数。但是,我收到错误:xor.cpp:(.text+0x35): undefined reference to "the function in header file" collect2: error: ld returned 1 exit status。看了这个post,我觉得编译步骤是OK的,也是因为我可以访问这个头文件里的变量,但是调用函数returns就出现上面说的错误。我的问题是:如何从 main.cpp 访问命名空间中的那些函数?我做错了什么?

class 的情况对我来说很清楚,但这里我不明白,因为我不应该创建对象,所以只调用前面的命名空间应该可以(?)。

编辑

根据Maestro 的建议修改后,我已经按照下面的方式更新了代码,但是还是不行。我得到的错误是一样的。如果我定义 using NEAT::trait_param_mut_prob = 6.7; 我会得到错误:xor.cpp:127:36: error: expected primary-expression before ‘=’ token

主要c++

#include "experiments.h"
#include "neat.h"
#include <cstring>

int main(){

  const char *the_string = "test.ne";
  bool bool_disp = true;
  NEAT::trait_param_mut_prob;
  trait_param_mut_prob = 6.7;
  NEAT::load_neat_params(the_string ,bool_disp);
  std::cout << NEAT::trait_param_mut_prob << std::endl;
  return 0;
}

neat.h

    #ifndef _NERO_NEAT_H_
    #define _NERO_NEAT_H_
    
    #include <cstdlib>
    #include <cstring>
    
    namespace NEAT {
        extern double trait_param_mut_prob;
        bool load_neat_params(const char *filename, bool output = false); //defined HERE 
    
    }
    #endif

neat.cpp

#include "neat.h"
#include <fstream>
#include <cmath>
#include <cstring>

double NEAT::trait_param_mut_prob = 0;

bool NEAT::load_neat_params(const char *filename, bool output) { 
                    //prints some stuff
                    return false;
                    };

生成文件

neat.o: neat.cpp neat.h
        g++ -c neat.cpp

您正在破坏 "ODR rule" (One-Definition-Rule):您在源文件 neat.cpp 中两次定义了 trait_param_mut_probload_neat_params,第二次在main.cpp 所以只需从 main.cpp:

中删除这些行
//double NEAT::trait_param_mut_prob; //NEAT is the namespace 
//bool NEAT::load_neat_params(const char* filename, bool output); //function defined in the namespace 
  • #endif在你headerneat.h.
  • 要使您的函数和变量在 main 中可用,只需使用 using 或 fully-qualify 调用,因为正如我所见,您打算 re-declare 它们在main 以避免完全限定它们:in main:

    int main()
    {
    
        using NEAT::trait_param_mut_prob;
        using NEAT::load_neat_params;
    
        const char* the_string = "test.ne";
        bool bool_disp = true;
        trait_param_mut_prob = 6.7;//works perfectly 
        load_neat_params(the_string, bool_disp);
        // or fully-qualify:
    
        //NEAT::load_neat_params(the_string, bool_disp);
        //NEAT::trait_param_mut_prob = 6.7;//works perfectly 
    }
    
  • 此外,您的函数 load_neat_params 没有 return 一个 bool 值也是错误的。所以要么 return true 要么 false.