我有以下文件:
includes/static.hpp
:#ifndef STATIC_HPP_
#define STATIC_HPP_
namespace static_namespace {
static void static_function();
static inline void static_inline_function();
}
#endif
src/static.cpp
:#include <iostream>
#include "static.hpp"
using namespace std;
using namespace static_namespace;
static void static_namespace::static_function(){
cout<<"Static"<<endl;
}
static inline void static_namespace::static_inline_function() {
cout<<"Static inline"<<endl;
}
src/main.cpp
:#include "static.hpp"
using namespace std;
using namespace static_namespace;
int main (int argc, const char *argv[]) {
static_function();
static_inline_function();
return 0;
}
完整的项目可以在这里找到。
编译上述文件时,出现以下信息:
[ 50%] Linking CXX executable main
/usr/bin/ld: CMakeFiles/main.dir/src/main.cpp.o: in the function `main':
main.cpp:(.text.startup+0x9): reference to `static_namespace::static_function()' not defined
/usr/bin/ld: main.cpp:(.text.startup+0xe): reference to `static_namespace::static_inline_function()' not defined
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:97: main] Error 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
是否可以将静态函数的实现与其声明分开定义?
谢谢和问候。
问题是你从未包含 static.cpp;因此,您试图调用一个尚未定义的函数。您需要在main.cpp文件中包含static.cpp:
#include "static.hpp"
#include "static.cpp"
using namespace std;
using namespace static_namespace;
int main (int argc, const char *argv[]) {
static_function();
static_inline_function();
return 0;
}
但是,这有可能在项目后期导致链接器错误;为了解决这个问题,请在每个文件的开头添加
#pragma once
(不包括 main.cpp 文件)