简体   繁体   中英

'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.

I see an error when I try to compile some C++ code (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.

I am compiling this code with the following (in a UNIX environment) -

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?

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).

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. When you start working with multiple files, it's a good time to start using a makefile , which can automate all the dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM