Error when compiling the code, linker command failed? - c++

I am relatively new to C++ and I am using CLions. I am trying to run this code as follows:
/*
* File: Warmup.cpp
* ----------------
#include <iostream>
#include <string>
#include "../lib/StanfordCPPLib/console.h"
#include "../lib/StanfordCPPLib/simpio.h"
using namespace std;
/* Constants */
const int HASH_SEED = 5381; /* Starting point for first cycle */
const int HASH_MULTIPLIER = 33; /* Multiplier for each cycle */
const int HASH_MASK = unsigned(-1) >> 1; /* All 1 bits except the sign */
/* Function prototypes */
int hashCode(string key);
/* Main program to test the hash function */
int main() {
string name = getLine("Please enter your name: John");
int code = hashCode(name);
cout << "The hash code for your name is " << code << "." << endl;
return 0;
}
/*
* Function: hash
* Usage: int code = hashCode(key);
* --------------------------------
int hashCode(string str) {
unsigned hash = HASH_SEED;
int nchars = str.length();
for (int i = 0; i < nchars; i++) {
hash = HASH_MULTIPLIER * hash + str[i];
}
return (hash & HASH_MASK);
}
However, I am getting the following errors:
[ 50%] Building CXX object CMakeFiles/Warmup.dir/src/Warmup.cpp.o
[100%] Linking CXX executable Warmup ld: library not found for
-llib/StanfordCPPLib clang: error: linker command failed with exit code 1 (use -v to see invocation) make[3]: * [Warmup] Error 1
make[2]: [CMakeFiles/Warmup.dir/all] Error 2 make[1]:
[CMakeFiles/Warmup.dir/rule] Error 2 make: * [Warmup] Error 2
I know that this works for microsoft studio C++ but I am not sure why it isnt running for CLions. Would someone mind giving some advice here ?
Any help would be greatly appreciated.
Thanks
Edit: This is what my current CMakeLists.txt file looks like:
cmake_minimum_required(VERSION 3.6)
project(0_Warmup)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILE src/Warmup.cpp)
link_libraries(lib/StanfordCPPLib)
add_executable(Warmup src/Warmup.cpp)
Am I making an error linking this library somewhere ?

I think u added above this //
#include "../lib/StanfordCPPLib/console.h"
#include "../lib/StanfordCPPLib/simpio.h"// library and u shud try once again a right path of library folder ..

Related

How do I resolve this error: expected unqualified-id before '-' token

Context: Preparing for the Fall semester, I whipped up a quick code file to check if you can call a function as a parameter of another function. However, before I could compile the code and check - this error happened.
C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g
\wsl$\kali-linux\home\tyrael\Foundry\morga.cpp -o
\wsl$\kali-linux\home\tyrael\Foundry\morga.exe
'\wsl$\kali-linux\home\tyrael\Foundry'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
In file included from
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:39,
from \wsl$\kali-linux\home\tyrael\Foundry\morga.cpp:1:
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ostream:681:49:
error: expected unqualified-id before '-' token
__rvalue_ostream_type<_Ostream>>::type - operator<<(_Ostream&& __os, const _Tp& __x)
^
Build finished with error(s).
The terminal process failed to launch (exit code: -1).
Terminal will be reused by tasks, press any key to close it.
I had tried moving around the #include statement, didn't work.
I tried to isolate the cause of the error by commenting out huge swaths of the code, but the error still there.
My only guess as far as what the issue could be is that the compiler is very angy that I am trying to call a function as a parameter for another function, but I can't verify that.
I'm truly at a loss, I just don't know what it could be. Any help would be much appreciated!
This is the code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
// Forward declaration of my functions
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
// simple function that takes numbers and combines them into one total sum
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
// simple function that takes a number and multiples by 5
int main (int argc, char** argv) {
combiner();
int final = multiplier(combiner());
cout << "This is our final number: " << final;
return 0;
}
// putting it all together, using a function as a parameter for another function
I remembered that you can't pass a func as a parameter for another func in C, but you can in other langs. However, even when I get rid of that process - I still hit the error. Here's the new code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
int main (int argc, char** argv) {
int tiago = combiner();
int final = multiplier(tiago);
// Storing return value of combiner() into a int variable, using that var as
// parameter instead for 2nd function - multiplier
cout << "This is our final number: " << final;
return 0;
}
EDIT: In the vein of investigating my compiler, here are some screenshots to show what my compilation process looks like on VS Code.
Selecting the compiler type
Select the actual compiler, the one I want is g++

How to solve multiple definition of `_start' error?

I am working on a project where I have to compare incoming data from a sensor. The main source code is in C++ along with a C source file, a .S file, and a .h file. When I am trying to link those files it shows an error and I don't have any clue as to what the error is. Any help regarding the problem will be very much appreciated.
My Makefile looks like:
all : main.cpp irq.c irq.h bootstrap.S
riscv32-unknown-elf-gcc -c irq.c bootstrap.S -march=rv32g -mabi=ilp32d -nostartfiles -Wl,--no-relax
riscv32-unknown-elf-g++ -c main.cpp -march=rv32g -mabi=ilp32d
riscv32-unknown-elf-g++ -o main main.o irq.o bootstrap.o -march=rv32g -mabi=ilp32d
dump-elf: all
riscv32-unknown-elf-readelf -a main
dump-code: all
riscv32-unknown-elf-objdump -D main
dump-comment: all
objdump -s --section .comment main
clean:
rm -f main`
main.cpp
#include "stdint.h"
extern "C"{
#include "irq.h"
}
#include<stdio.h>
#include<iostream>
using namespace std;
static volatile char * const TERMINAL_ADDR = (char * const)0x20000000;
static volatile char * const SENSOR_INPUT_ADDR = (char * const)0x50000000;
static volatile uint32_t * const SENSOR_SCALER_REG_ADDR = (uint32_t * const)0x50000080;
static volatile uint32_t * const SENSOR_FILTER_REG_ADDR = (uint32_t * const)0x50000084;
bool has_sensor_data = 0;
void sensor_irq_handler() {
has_sensor_data = 1;
}
void dump_sensor_data() {
while (!has_sensor_data) {
asm volatile ("wfi");
}
has_sensor_data = 0;
for (int i=0; i<64; ++i) {
*TERMINAL_ADDR = *(SENSOR_INPUT_ADDR + i) % 92 + 32;
}
*TERMINAL_ADDR = '\n';
}
int main() {
register_interrupt_handler(2, sensor_irq_handler);
*SENSOR_SCALER_REG_ADDR = 5;
*SENSOR_FILTER_REG_ADDR = 2;
for (int i=0; i<3; ++i)
dump_sensor_data();
return 0;
}
irq.c
https://github.com/agra-uni-bremen/riscv-vp/blob/master/sw/simple-sensor/irq.c
irq.h
https://github.com/agra-uni-bremen/riscv-vp/blob/master/sw/simple-sensor/irq.h
bootstrap.S
https://github.com/agra-uni-bremen/riscv-vp/blob/master/sw/simple-sensor/bootstrap.S
The output should be 64 random characters with interrupts.
The Error is:
/opt/riscv/lib/gcc/riscv32-unknown-elf/8.3.0/../../../../riscv32-unknown-elf/bin/ld: /tmp/cckjuDlw.o: in function `.L0 ':
(.text+0x0): multiple definition of `_start'; /opt/riscv/lib/gcc/riscv32-unknown-elf/8.3.0/../../../../riscv32-unknown-elf/lib/crt0.o:(.text+0x0): first defined here
You're using the -nostartfiles option, but in the wrong place.
You have it on a compilation step (-c option), while it belongs on linking.
-Wl, options are also only used when linking

Segfault after adding #pragma loop

I faced a little trouble. I'm not sure if I can understand it.
So, I have some code. And I'm trying to add #pragma loop(hint_parallel(8)) statement for a few loops in the code.
When I compile that using necessary compilation options which are actually like this:
gcc -w -funroll-loops -O2 -fno-inline -fipa-pta -msse2
-funsafe-math-optimizations -ftree-vectorizer-verbose=1 -fopt-info-optimized=logs/optOpt.txt -shared -fPIC singleThread.cpp
I get segmentation fault.
fish: './a.out' terminated by signal SIGSEGV (Address boundary error)
The point is that I have no idea why it is. I suspected that it could be a problem with a constant that is used in these loops. But I don't think that this is related. if I just compile this code using -O0 optimisation it works fine (because complier doesn't vectorise something I guess).
Could you please take a look on the code below and suggest me in which direction I should check.
Thanks.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <random>
#include <cstdio>
#include <set>
#include <fstream>
#include <cstdint>
#include <climits>
using namespace std;
const int STRING_HASH_SIZE = 32;
int convert(vector<string> &inputVector, const char **outputArray);
void printCollisions(const char **charArray, int size);
void printArray(const char **arrayToPrint, int size);
int getHashCode(const char *characters, unsigned long size);
string getRandomString();
void writeFileIfNeeded(vector<string> &vector, bool needToWrite);
vector<string> generateStringsVector(int size, bool isNeedToWriteFile);
/**
* main method is present to test these native code.
* to perform some external operation we should use another method.
* #return
*/
int main() {
/**
* The constant represents number of strings that will be generated
* in the string vector generation.
*/
const int STRING_NUMBERS = 100000;
vector<string> inputVector = generateStringsVector(STRING_NUMBERS, false);
#pragma pack 8
const char *charArray[inputVector.size()];
int hashResult = convert(inputVector, charArray);
if (hashResult != 0) {
return 0;
}
printCollisions(charArray, STRING_NUMBERS);
}
/**
* Converts an input vector to char array.
* Getting a hash of
* Returns 0 if conversion from vector to array has been successfully performed.
* #param inputVector [ input array reference ]
* #param outputArray [ a char array that would contain char sequences from vector ]
* #return [ hash sum (int)]
*/
int convert(vector<string> &inputVector, const char **outputArray) {
int hashSum = 0;
#pragma loop(hint_parallel(8))
for (int i = 0; i < inputVector.size(); i++) {
outputArray[i] = inputVector[i].c_str();
}
#pragma loop(hint_parallel(8))
for (auto &i : inputVector) {
hashSum += getHashCode(i.c_str(), i.length());
}
int stringHashSize = STRING_HASH_SIZE;
#pragma loop(hint_parallel(8))
for (int i = 0; i < inputVector.size(); i++) {
hashSum -= getHashCode(outputArray[i], stringHashSize);
}
if (hashSum != 0) {
cout << "\nConversion isn't succeeded, hash = " << hashSum << endl;
} else {
cout << "\nConversion succeeded" << endl;
}
return hashSum;
}
/**
* Prints count and percentage of collisions in array hash codes
* #param charArray
* #param size
*/
void printCollisions(const char **charArray, int size) {
set<int> setOfHashes;
int stringHashSize = STRING_HASH_SIZE;
#pragma loop(hint_parallel(8))
for (int i = 0; i < size; i++) {
setOfHashes.insert(getHashCode(charArray[i], stringHashSize));
}
unsigned long collisions = size - setOfHashes.size();
cout << collisions << "/" << size << " " << 100.0 * collisions / size << "% of collisions";
}
/**
* Prints input char array
* #param arrayToPrint
*/
void printArray(const char **arrayToPrint, int size) {
cout << "\nPrinted array size = " << size << endl;
for (int i = 0; i < size; i++) {
cout << arrayToPrint[i] << ":" << getHashCode(arrayToPrint[i], STRING_HASH_SIZE) << endl;
}
}
/**
*
* #param characters
* #return
*/
int getHashCode(const char *characters, unsigned long size) {
int hash = 0;
#pragma loop(hint_parallel(8))
for (int i = 0; i < size; i++) {
hash = (31 + hash) * (characters[i]);
}
return hash;
}
/**
* Get a random String from alphabetical char sequence.
* #return a randomized string according to an alphabet.
*/
string getRandomString() {
string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
random_device rd;
mt19937 generator(rd());
shuffle(str.begin(), str.end(), generator);
return str.substr(0, STRING_HASH_SIZE);
}
/**
* Generates a vector with random strings
* #param size - an int value that will be used as size of a generated vector
* #return reference to generated vector.
*/
vector<string> generateStringsVector(int size, bool isNeedToWriteFile) {
vector<string> charArray;
#pragma loop(hint_parallel(8))
for (int i = 0; i < size; i++) {
string str = getRandomString();
charArray.push_back(str);
}
writeFileIfNeeded(charArray, isNeedToWriteFile);
return charArray;
}
/**
* Writes file with name according to vector size (e.g. 100000.csv)
* if needToWrite is true
* #param vector
* #param needToWrite
*/
void writeFileIfNeeded(vector<string> &vector, bool needToWrite) {
if (needToWrite) {
ofstream csvFile;
string filename = to_string(vector.size()) + ".csv";
csvFile.open(filename, fstream::out);
for (const auto &i : vector) {
csvFile << i << "\n";
}
csvFile.close();
}
}
What is causing the segmentation fault is the way you compile your code and not the pragmas (which don't have any effect in gcc anyway, see below):
gcc -w -funroll-loops -O2 -fno-inline -fipa-pta -msse2
-funsafe-math-optimizations -ftree-vectorizer-verbose=1 -fopt-info-optimized=logs/optOpt.txt -shared -fPIC singleThread.cpp
By using -shared -fPIC you are creating a DSO (dynamic shared object). If you try to execute this file, you'll get an invalid PC (program counter) and your program will crash immediately. You must compile your code without -shared -fPIC (and use -pie -fPIE if you need a position-independent executable).
Also, for compiling C++ code you should normally use g++ instead of gcc.
The given pragmas should not have any effect on your code, as these ones are only understood by Microsoft Visual Studio. Add -Wall to your compile options and gcc will show you the respective warnings.
In any case, you should get rid of vendor-specific pragmas and use standardized solutions like OpenMP instead (compile with -fopenmp). That way, you are a step closer to writing compiler-independent code.
As for the parallelized loops, you should make sure you don't run into race conditions or other synchronization failures. For example, to compute a sum, #pragma omp parallel for reduction(+: sum) is your friend in OpenMP (reference sheet).
Disclaimer: I have used gcc 7.3.0 on x86_64 (CentOS Linux).

How to fix architecture x86_64 errors?

I'm running omnet++ 4.6 for around 6months now. When I tried building my project after a few changes:
removing a header file from the project
adding more files to my includes folder
I get this error
Creating shared library: ../out/gcc-debug/src/libinet.dylib
Undefined symbols for architecture x86_64:
"BloomFilter::BloomFilter(unsigned long, int, unsigned long, ...)", referenced from:
AODVRouting::AODVRouting() in AODVRouting.o
AODVRouting::AODVRouting() in AODVRouting.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[1]: *** [../out/gcc-debug/src/libinet.dylib] Error 1
make: *** [all] Error 2
My project used to build and run fine before this.
This is .cc file:
#include "BloomFilter.h"
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <cstdarg>
#include <exception>
#include <stdio.h>
#include <string.h>
using namespace std;
#define SETBIT(a, n) (a[n/CHAR_BIT] |= (1<<(n%CHAR_BIT)))
#define GETBIT(a, n) (a[n/CHAR_BIT] & (1<<(n%CHAR_BIT)))
// The Constructor
BloomFilter::BloomFilter(size_t size,int hash_k, size_t nfuncs, ...) {
va_list l;
unsigned int n;
try {
this->a=new char[(size+CHAR_BIT-1)/CHAR_BIT];
}
catch(const std::exception& e)
{
// If we get here is that there is an allocation error .
// We must free the memory .
delete(this);
// std :: cerr << "ERROR: " << e.what () << endl;
// Then raise the exception to indicate that an error occurred.
throw;
}
try {
this->funcs= new hashfunc_t[nfuncs];
}
catch(const std::exception& e){
delete(this->a);
delete(this);
}
va_start(l, nfuncs);
for(n=0; n < nfuncs; ++n) {
this->funcs[n]=va_arg(l, hashfunc_t);
}
va_end(l);
this->nfuncs=nfuncs;
this->asize=size;
this->hash_k=hash_k;
}
// The Destructor
BloomFilter::~BloomFilter() {
/*
delete(this->a);
delete(this->funcs);
delete(this);
*/
}
int BloomFilter::AddToBloom(std::string word){
char t= '1';
int AddFlag; // to know if the element is added successfully
for(int i=0;i<this->hash_k;i++){
AddFlag=Add(word += t);
t++;
}
return AddFlag;
}
int BloomFilter::Add(std::string word){
size_t size = word.size() + 1;
char * buffer = new char[ size ];
strncpy( buffer, word.c_str(), size );
return Add(buffer);
}
int BloomFilter::Add(const char *s)
{
size_t n;
for(n=0; n<this->nfuncs; ++n) {
SETBIT(this->a, this->funcs[n](s)%this->asize);
}
return 0;
}
int BloomFilter::CheckBloom( std::string word){
int CheckFlag;
char t= '1';
for(int i=0;i<this->hash_k;i++){
if(!Check(word += t)) return 0;
t++;
}
return 1;
}
int BloomFilter::Check(std::string word){
size_t size = word.size() + 1;
char * buffer = new char[ size ];
strncpy( buffer, word.c_str(), size );
return Check(buffer);
}
int BloomFilter::Check(const char *s)
{
size_t n;
for(n=0; n< this->nfuncs; ++n) {
if(!(GETBIT(this->a, this->funcs[n](s)%this->asize))) return 0;
}
return 1;
}
//Print information about this object
void BloomFilter::toString(){
/*EV << "[BloomFilter] Hello, I am ready ? " << ready
<<" ; max entry :" << maxEntry << endl;*/
}
What's the fix for this error?
That's a linker, not a C++ compiler error. You will probably have to add the .o file generated from you .cc file to the list of objects that get linked together to form libinet.dylib
I got rid of this error after copying files .cc and .h from my root project to the project I'm working on (in the specified directory).
I did this while running omnet++ and within the projects browser.
I'm not sure how does that link to the "linker" problem but it definitely solved mine.

Linking error while using static library linkage

This might have been asked previously, however, I found it only in context of Classes, and this is not the case.
Utils.h
#ifndef _UTILS_H_
#define _UTILS_H_
#include <cmath>
//is 'x' prime?
bool isPrime(long long int x);
//find the number of divisors of 'x' (including 1 and x)
int numOfDivisors(long long int x);
#endif //_UTILS_H_
Utils.cpp
#include "Utils.h"
bool isPrime(long long int x){
if (x < 2){
return false;
}
long double rootOfX = sqrt( x );
long long int flooredRoot = (long long int)floor ( rootOfX );
for (long long int i = 2; i <= flooredRoot; i++){
if (x % i == 0){
return false;
}
}
return true;
}
int numOfDivisors(long long int x){
if (x == 1){
return 1;
}
long long int maxDivisor = (x / 2) + 1;
int divisorsCount = 0;
for (long long int i = 2; i<=maxDivisor; i++){
if (x % i == 0){
divisorsCount++;
}
}
divisorsCount += 2; //for 1 & x itself
return divisorsCount;
}
These two files have been compiled with Visual Studio 2012 in Debug mode as a static library.
Now I try to use them in a separate project, let's call it MainProject:
1. Add the "Utils.vcproj" to MainProject solution.
2. Make MainProject to depend on Utils
3. In "Properties"->"Linker"->"Input"->"Additional Dependencies" put the path to Utils.lib
Here is the main which uses Utils:
#include <iostream>
#include "..\Utils\Utils.h"
using namespace std;
int main(){
cout << "num of divisors of " << 28 << ": " << numOfDivisors(28) << endl;
//this part is merely to stop visual studio and look at the output
char x;
cin >> x;
return 0;
}
And this is the error I get:
Error 1 error LNK2019: unresolved external symbol "int __cdecl numOfDivisors(__int64)" (?numOfDivisors##YAH_J#Z) referenced in function _main G:\ProjectEuler\Problem12\Source.obj Problem12
Why can't it find the code which implements "numOfDivisors"? I have given it the .lib which contains it, moreover - put a dependency on the Utils project itself...
Any help would be appreciated.
Assuming the library is correctly built and linked, the next most likely cause of the error is that the function is named something else in the library than it is in the code that links to it.
This could be caused by any number of project settings that affect either name decoration or type names. There's not really any point in guessing from a distance which particular setting is the culprit in your case. You can compare the two projects' properties (either manually or with a diff tool) and try to spot a difference that would result in a different decorated function name.
Looks like method numOfDivisors() is not defined in you Utils.cpp, can you check it once?
And why is your compiler complaining "G:\ProjectEuler\Problem12\Source.obj"? Where is Source.obj coming from?
You have to specify library path in one field and library name in other field, have you specified both under appropriate settings?