[英]'Undefined reference to' error in C++ although function definition exists in header file in include path
Please bear with me if this is a naive question. 如果这是一个幼稚的问题,请忍受我。 I tried to see if this was answered elsewhere on SO, but I didn't quite find a question that answered this.
我试图查看是否在SO的其他地方得到了回答,但是我没有找到一个可以回答这个问题的问题。
I see an error when I try to compile some C++ code (test.cpp). 当我尝试编译一些C ++代码(test.cpp)时,我看到一个错误。 I am including some headers, as follows -
我包括一些标题,如下所示-
#include <iostream>
#include <string>
#include "lefrReader.hpp"
lefrReader.hpp has the definition of function lefrInit(), and is present in the folder /foo/bar/include, say. lefrReader.hpp具有函数lefrInit()的定义,例如位于/ foo / bar / include文件夹中。
I am compiling this code with the following (in a UNIX environment) - 我正在使用以下代码(在UNIX环境中)编译此代码-
g++ -I/foo/bar/include -L/foo/bar/include ./test.cpp -o ./test
However, this fails with this error - 但是,此失败并显示此错误-
test.cpp:(.text+0x11): undefined reference to `lefrInit()'
collect2: ld returned 1 exit status
Shouldn't having the /foo/bar/include directory in the include (-I) path help with finding lefrReader.hpp? 包含(-I)路径中的/ foo / bar / include目录是否应该有助于查找lefrReader.hpp?
EDIT - I also tried the following to no avail (from What is an undefined reference/unresolved external symbol error and how do I fix it? ) - 编辑-我也尝试了以下尝试(从什么是未定义的引用/未解决的外部符号错误以及如何解决它? )-
g++ -I/foo/bar/include -L/foo/bar/include ./test.cpp -o ./test -llefrReader
Error - 错误-
test.cpp:(.text+0x11): undefined reference to `lefrInit()'
collect2: ld returned 1 exit status
-l
is for linking with libraries, so -llefRreader
looks for lefrReader.a
(static library) or lefrReader.so
(shared library). -l
用于链接库,因此-llefRreader
查找lefrReader.a
(静态库)或lefrReader.so
(共享库)。
To link with a single object file, you just put the object file as an argument. 要链接单个目标文件,只需将目标文件作为参数即可。
g++ -I/foo/bar/include ./test.cpp /foo/bar/include/lefrReader.o -o ./test
You have to previously compile that file: 您必须事先编译该文件:
g++ -I/foo/bar/include lefrReader.cpp -c -o lefrReader.o
Or you can compile and link them both at once: 或者,您可以一次编译并链接它们:
g++ -I/foo/bar/include ./test.cpp /foo/bar/include/lefrReader.cpp -o ./test
However, this means you'll recompile both .cpp
files even when just one of them has changed. 但是,这意味着即使其中一个已更改,您也将重新编译两个
.cpp
文件。 When you start working with multiple files, it's a good time to start using a makefile
, which can automate all the dependencies. 当您开始使用多个文件时,现在是开始使用
makefile
的好时机,该makefile
可以使所有依赖项自动化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.