简体   繁体   中英

How to link .cpp file to .h file for a downloaded library

I am very new to C++, and I have been completing the exercises for the Stanford 106B CS class. I've found a lot of posts here and elsewhere with a similar problem to mine, but none that could help me out with my specific issue. The Stanford 106B class uses the StanfordCPPlib, or Stanford c++ libraries, which I downloaded. I am trying to complete an exercise that requires me to #include "random.h" so I can use a method for finding a random real number between 0 and 1. Anyways, simply writing #include "random.h" and the rest of the necessary code in text file doesn't work. I am getting this error:

make random
c++     random.cpp   -o random
Undefined symbols for architecture x86_64:
  "randomReal(double, double)", referenced from:
      _main in random-BBexsD.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [random] Error 1

The Stanford class uses Xcode, and the homework assignments downloaded from the website have Xcode projects already set up to run with the Stanford libraries. There is also a blank Xcode project template to use for the text book exercises. However, I am trying to figure out how to do this in a text editor or terminal or both. I usually write all my code using a text editor and executing it in terminal. I have tried writing #include "file_path_to_stanford_libraries/random.h", which I'm not even sure works in a .cpp file, but I tried it to no avail. I tried putting the files in the exact same directory as my random.cpp file, which also didn't work. Sorry for this long, and hopefully, not inane post. I appreciate any help.

That linker error normally means that the header file is being included just fine, but the library however, isn't included. I don't know Clang, so can't give a full answer for you, but for g++, you'd need to find the library file and make sure its directory is in your LD_LIBRARY_PATH, then take its name; it will be something like "lib StanfordCPP .so". You then need add a flag to the linker on the command line that contains the bolded part of the name (between lib and file extension) after -l (hyphen-L), so here that would be -lStanfordCPP .

Your command line then looks something like:

g++ -o bin/random random.cpp -lStanfordCPP

Unfortunately this isn't Clang, but it ought to work about the same. If someone else would like to provide the Clang way (or verify you can do this with Clang) that'd be great.

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