Converting an array of bytes to int gives Apple Mach-O linker error

Dec 8, 2016 at 3:13am
I am trying to convert an array of bytes into an integer. In Java, I do the following:

1
2
3
4
5
6
7
8
9
10
11
12
  public static int bytesToInt(byte[] b) 
    {
        int result = 0;
        
        for (int i = 0; i < b.length; i++) 
        {
            result <<= 8;
            result |= (b[i] & 0xFF);
        }
        
        return result;
    }


I tried to apply the same approach in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  typedef unsigned char BYTE;


  int bytesToInt(BYTE b[], int n)
  {
    int result = 0;
    
    for (int i = 0; i < n; i++)
    {
        result <<= 8;
        result |= (b[i] & 0xFF);
    }
    
    return result;
  }


And calling this from another class:

1
2
3
4
5
6
7
8
9
  IGAByteConversion *windObj = new IGAByteConversion();
    
  IGAByteConversion::BYTE test[4]={0xb4,0xaf,0x98,0x1a};
    
  int  convert = windObj->bytesToInt(test,4);

  std::cout<<std::endl<<convert;
    
  delete windObj;


I get an error in Xcode saying:

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I wonder if this is because there is something wrong with the code or because of the project settings. Thank you!
Last edited on Dec 8, 2016 at 3:21am
Dec 8, 2016 at 3:49am
> I wonder if this is because there is something wrong with the code or because of the project settings.

The linker error is probably because the source file has not been added to the project.

In your code, you may want to take care of endianness.
https://en.wikipedia.org/wiki/Endianness
Dec 8, 2016 at 4:40am
closed account (48T7M4Gy)
In my experience that linker error code in Xcode is often, but not always, accompanied with other error messages. A common one is where you are compiling a set of files that don't have a main() function. Project setting don't need to be changed in that case, all you need is the relevant file with main() in it.

Failing that it might be some other function not linking.

There are 3 parts, not just 1:
Apple Mach-O Linker (ld) Error Group
"_main", referenced from:
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Dec 9, 2016 at 3:07am
It has been a long time since I programmed in C++. Solved by renaming the class with the main method to "main". ;-)

Thank you!
Last edited on Dec 9, 2016 at 3:08am
Topic archived. No new replies allowed.