Cygwin undefined reference to adjtime - c

this is my first time posting a question here so be kind :).
I have a problem porting a linux application to windows (windows 7 64-bit) using cygwin. I had to rewrite some code that is not supported under windows and that doesn´t exist in cygwin (like adjtimex) and I have manage to compile the code but when I am building the application .exe file (by using makefiles) I get a link error:
gcc -Wl,-Map,ppsi.map2 -o ppsi ppsi.o -lrt -lc
ppsi.o: In function `win_time_adjust':
ppsi/time-win/win-time.c:74: undefined reference to `adjtime'
ppsi/time-win/win-time.c:74:(.text+0x1905): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `adjtime'
adjtime function is defined in which is included in the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h> /* timex.h not available on windows so we use sys/time.h*/
#include <ppsi/ppsi.h>
Here is how a part of the code looks like:
static int win_time_adjust(struct pp_instance *ppi, long offset_ns, long freq_ppb){
struct timeval t;
int ret;
t.tv_sec = 0;
t.tv_usec = 0;
if (offset_ns) {
t.tv_sec = offset_ns / 1000000;
t.tv_usec = offset_ns / 1000; /*microseconds */
}
ret = adjtime(&t, NULL);
pp_diag(ppi, time, 1, "%s: %li %li\n", __func__, offset_ns, freq_ppb);
return ret;
}
I have encountered a similar problem before and I solved by linking the missing library when compiling the application. I tired the same here and linked libc (since adjtime is suppose to be there) -lc when compiling but got the same error. I unsure how adjtime is undefined and I wonder if there is some cygwin library I should link instead?
I use cygwin (gcc version 4.9.2) when compiling

From my understanding, adjtime is a Linux-ism which likely crawled its way into the BSD world via FreeBSD. It's certainly not documented by any of the C or POSIX standards.
Even those which are documented by the C and POSIX standards often aren't implemented correctly in the Microsoft world, so it wouldn't surprise me that this function doesn't exist.
I'm very interested to hear more about this project of yours. Though a simplistic wrapper of some implementation-defined stuff can be written for the purposes of portability, I can only imagine highly niche usecases, for which there are better alternatives:
If you need something with a large amount of good, secure entropy to seed your pseudo-random number generator, you should use something provided by a cryptographic library.
If you want to conduct performance tests, you should learn how to use the profiler rather than rolling your own profiling code. Also, every "performance test" should be conducted as though through the eyes of a scientist observing the very first time; it's generally best not to let tests from previous projects guide optimisation for future projects. Instead, let the profile of the current project guide optimisation for the current project (on the current hardware), and you'll be cheering before you know it!

Related

C pthread including header file and linking with -nolibc

This example:
#include <stdio.h>
#include <pthread.h>
__attribute__((weak)) int pthread_create( pthread_t*, const pthread_attr_t*,
void*(*)(void*), void*);
int main()
{
if (pthread_create)
{
printf("This is multi-thread version!\n");
}
else
{
printf("This is single-thread version!\n");
}
return 0;
}
It says it is going to run in single thread mode if not linked to the pthread library but with the #include pthread isn't it going to be linked if compiled normally?
I think pthread is in glibc or libc but firstly is there a way to link excluding the standard library and if so when would you do that?
If there is code that can be run in multithread mode, is there ever any point in running it in single thread mode as in the example or is this just a bad example? If so, what is a better example of hard-coding in something as a weak symbol?
but with the #include pthread isn't it going to be linked if compiled normally?
No, including a header file is different from linking with a library.
I think pthread is in glibc or libc
It is not.
is there a way to link excluding the standard library
Check your compiler documentation. gcc has many link options like -nolibc -nostdlib nodefaultlibs.
if so when would you do that?
When I am compiling for a bare-metal target that indeed has no C library. When I am writing my own standard library or I want to use a different C library then the default one distributed with the system or when crosscompiling I have a custom C library in a custom location and system doesn't ship one with the crosscompiler. Etc.
If there is code that can be run in multithread mode, is there ever any point in running it in single thread mode`
Yes. For some reasons multithreading would results in worse performance when compared to single thread, like on a single core system. In case a realtime process that owns cpu anyway. Or in case a particular algorithm can't be multithreaded or would results in worse performance when multithreaded.

Program memory not increasing when including math.h library

I'm a bit of a newbie to the Atmel world. Once Upon a time I could write and compile C with Visual Studio but am a bit out of practice.
So I'm trying to get an understanding of memory usage in a microcontroller ATTINY1616. I opened Atmel studios, created a C executable project and chose the correct microcontroller. I build the project which has next to nothing in it and see that the program memory is 154 bytes. This is my baseline.
Now I tried to add the line #include <math.h> to see if my program memory usage would increase. It didn't. Then I tried adding float a = 2.000678f; inside the main. Still no increases after building the project. What am I misunderstanding here?
/*
* GccApplication2.c
*
* Created: 12/20/2018 9:21:43 PM
* Author : joely
*/
#include <avr/io.h>
#include <math.h>
int main(void)
{
float a = 2.000678f;
/* Replace with your application code */
while (1)
{
}
}
Header files typically only contain declarations of functions, not the definitions.
You're not using any of the functions declared in math.h, so the library they reside in isn't getting linked into your program. If you use one of them, for example float b = sin(a), then the contents of the math library is required and is linked in (assuming you pass -lm to gcc to do so).
So after asking some friends with microcontroller experience I found the solution.
In Atmel Studio you need to go to Project-->Application Properties--->Toolchain and Change optimization to none.
Then it recognizes my floats and stores them in program memory, and when atan() is used to perform a calc it also fills up the space with the same above code.

clock_gettime on MacOS

clock_gettime doesn't work on MacOS Sierra anymore. Pretty sure I had this compiling correctly before Xcode 8 came out. I am really kind of stuck on what to do to get it to compile correctly.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(){
struct timespec time1, time2;
clock_gettime(CLOCK_MONOTONIC,&time1);
//Some code I am trying to work out performance of...
clock_gettime(CLOCK_MONOTONIC,&time2);
printf("Time Taken: %ld",time2.tv_nsec - time1.tv_nsec);
}
Code like this simply fails to compile. I've been told the sierra timing library has changed. I get a compiler error for CLOCK_MONOTONIC not being defined and a warning for implicit declaration of clock_gettime, which turns into an error if I define CLOCK_MONOTONIC to something random, as it then just errors out during the linking stage.
Does anyone know of a fix or workaround to get the code compiling and executing?
I don't think CLOCK_MONOTONIC has been around in recent times.
I believe what you want is probably mach_absolute_time() plus a conversion, as documented here; this appears to be monotonic, and absolute (which are two different things as you probably know).
Other useful hints are to be found at the following related (but I think not duplicate) questions:
clock_gettime alternative in Mac OS X (but deals with a different clock type)
Monotonic clock on OSX (not C but objective C)

Undefined reference to 'strnlen' despite "string.h" include

I am trying to use create a project for LPC1769 on LPCXpresso. I have a C file calling
#include <string.h>
int main()
{
//some stuff
strnlen(SomeString, someInt);
}
to which I get an error:
Undefined reference to 'strnlen'
The weird part is that there is no problem with strcpy, strncpy or other common string functions.
I am building for a Cortex-M3 processor
Compiler used is: arm-none-eabi-gcc
In Eclipse, I have ticked the MCU linker option : No startup or default libs
I am running Eclipse on Ubuntu
While it may be easy enough to bypass this by just using strlen, I am actually facing a problem using a library which uses strnlen, and I don't want to mess with the library source.
The strnlen function was (until fairly recently) a Linux-specific function (some documentation such as the GNU libc manual still says that it is a "GNU extension"). The current manual page says it is part of POSIX.1-2008. Since you are cross-compiling, it is possible that the target machine's runtime library does not have this function. A forum posting from 2011 said just that.
I add the same problem and I found out that using -std=gnu++11 compiler flag solves it.
The following may work for you (since strnlen() is not a part of the runtime lib).
Define your own/local version of the strnlen().
int strnlen(char *param, int maxlen)
{
// Perform appropriate string manipulation ... as needed.
// Return what you need.
};
You want this include instead:
#include <string.h>
The difference between <> and "" is that <> searches for header files in your systems include folder. The "" searches for header files in the current directory and in any other include folders specified by -I directory

Compile different code on whether a function is available or not

Windows provides only GetTickCount up to Windows Vista and starting from that OS also GetTickCount64. How can I make a C program compile with calls to different functions?
How can I make a C compiler check whether a function is declared in the included header files and compile different portions of code depending on whether that particular function is available or not?
#if ??????????????????????????????
unsigned long long get_tick_count(void) { return GetTickCount64(); }
#else
unsigned long long get_tick_count(void) { return GetTickCount(); }
#endif
Looking for a working sample file not just hints.
Edit: I tried the following using gcc 3.4.5 from MinGW on a (64-bit) Windows 7 RC but it didn't help. If this is a MinGW problem, how can I work around this issue?
#include <windows.h>
#if (WINVER >= 0x0600)
unsigned long long get_tick_count(void) { return 600/*GetTickCount64()*/; }
#else
unsigned long long get_tick_count(void) { return 0/*GetTickCount()*/; }
#endif
Compile time selection of an API based on the target Windows version locks the built executable to that version and newer. This is a common technique for open source, *nix targeted projects where it is assumed that the user will configure the source kit for his platform and compile clean to install.
On Windows, this is not the usual technique because it isn't generally safe to assume that an end user will have a compiler at all, let alone want to deal with the intricacies of getting a project to build.
Often, just using the older API that is present in all versions of Windows is a sufficient answer. This is also simple: you just ignore the existence of a new API.
When that isn't sufficient, you use LoadLibrary() and GetProcAddress() to attempt to resolve the new symbol at run time. If it can't be resolved, then you fall back to the older API.
Here's a possible implementation. It detects the first call, and at attempts to load the library and resolve the name "GetTickCount64". In all calls, if the pointer to resolved symbol is non-null, it calls it and returns the result. Otherwise, it falls back on the older API, casting its return value to match the wrapper's type.
unsigned long long get_tick_count(void) {
static int first = 1;
static ULONGLONG WINAPI (*pGetTickCount64)(void);
if (first) {
HMODULE hlib = LoadLibraryA("KERNEL32.DLL");
pGetTickCount64 = GetProcAddressA(hlib, "GetTickCount64");
first = 0;
}
if (pGetTickCount64)
return pGetTickCount64();
return (unsigned long long)GetTickCount();
}
Note that I used the ...A flavors of the API functions since it is known that the library name and the symbol name will only be ASCII... if using this technique to load symbols from an installed DLL that might be in a folder named with non-ASCII characters, then you will need to worry about using a Unicode build.
This is untested, your mileage will vary, etc...
You can achieve it using preprocessor definitions in Windows headers.
unsigned long long
get_tick_count(void)
{
#if WINVER >= 0x0600
return GetTickCount64();
#else
return GetTickCount();
#endif
}
The right way to deal with this kind of problems is to check whether the function is available, but this cannot be done reliably during the project compilation. You should add a configuration stage, which details depend on your build tool, both cmake and scons, two cross platforms build tools, provide the facilities. Basically, it goes like this:
/* config.h */
#define HAVE_GETTICKSCOUNT64_FUNC
And then in your project, you do:
#include "config.h"
#ifdef HAVE_GETTICKSCOUNT64_FUNC
....
#else
...
#endif
Although it looks similar to the obvious way, it is much more maintainable in the long term. In particular, you should avoid as much as possible to depend on versions, and check for capabilities instead. Checking for versions quickly leads to complicated, interleaved conditionals, whereas with the technique above, everything is controlled from one config.h, hopefully generated automatically.
In scons and cmake, they will have tests which are run automatically to check whether the function is available, and define the variable in the config.h or not depending on the check. The fundamental idea is to decouple the capability detection/setting from your code.
Note that this can handle cases where you need to build binaries which run on different platforms (say run on XP even if built on Vista). It is just a matter of changing the config.h. If dones poperly, that's just a matter of changing the config.h (you could have a script which generate the config.h on any platform, and then gather config.h for windows xp, Vista, etc...). I don't think it is specific to unix at all.
Previous answers have pointed out checking for the particular #define that would be present for your particular case. This answer is for a more general case of compiling different code whether a function is available or not.
Rather than trying to do everything in the C file itself, this is the sort of thing where configure scripts really shine. If you were running on linux, I would point you to the GNU Autotools without hesitation. I know there's ports available for Windows, at least if you're using Cygwin or MSYS, but I have no idea how effective they are.
A simple (and very very ugly) script that could work if you have sh handy (I don't have a Windows setup handy to test this on) would look something like this:
#!/bin/sh
# First, create a .c file that tests for the existance of GetTickCount64()
cat >conftest.c <<_CONFEOF
#include <windows.h>
int main() {
GetTickCount64();
return 0;
}
_CONFEOF
# Then, try to actually compile the above .c file
gcc conftest.c -o conftest.out
# Check gcc's return value to determine if it worked.
# If it returns 0, compilation worked so set CONF_HASGETTICKCOUNT64
# If it doesn't return 0, there was an error, so probably no GetTickCount64()
if [ $? -eq 0 ]
then
confdefs='-D CONF_HASGETTICKCOUNT64=1'
fi
# Now get rid of the temporary files we made.
rm conftest.c
rm conftest.out
# And compile your real program, passing CONF_HASGETTICKCOUNT64 if it exists.
gcc $confdefs yourfile.c
This should be easy enough to translate into your scripting language of choice. If your program requires extra include paths, compiler flags, or whatever, make sure to add the necessary flags to both the test compile and the real compile.
'yourfile.c' would look something like this:
#include <windows.h>
unsigned long long get_tick_count(void) {
#ifdef CONF_HASGETTICKCOUNT64
return GetTickCount64();
#else
return GetTickCount();
#endif
}
You're asking about C but the question is tagged C++ as well ...
In C++ you would use SFINAE technique, see similar questions:
Is it possible to write a template to check for a function's existence?
But use preprocessor directives in Windows when provided.
If your code is going to run on OSes berfore Vista, you can't just compile your calls down to GetTickCount64(), because GetTickCount64() doesn't exist on an XP machine.
You need to determine at runtime which operating system you are running and then call the correct function. In general both calls need to be in the code.
Now this may not be true in your case if you don't really need to be able to call either GetTickCount64() on Vista+ machines and GetTickCount() on XP- machines. You may be able to just call GetTickCount() no matter what OS you're running on. There is no indication in the docs that I have seen that they are removing GetTickCount() from the API.
I would also point out that maybe GetTickCount() isn't the right thing to use at all. The docs say it returns a number of milliseconds, but in reality the precision of the function isn't even close to 1 millisecond. Depending on the machine (and there's no way to know at runtime AFAIK) the precision could be 40 milliseconds or even more. If you need 1 millisecond precision you should be using QueryPerformanceCounter(). In fact, there's really no practical reason to not use QPC in all cases where you'd use GetTickCount() anyway.
G'day,
Isn't NTDDI_VERSION what you need to look for?
Update: You want to check if WINVER is 0x0600. If it is then you're running Vista.
Edit: For the semantic pecker head, I meant running a compiler in a Vista environment. The question only refers to compiling, the question only refers to header files which are only used at compile time. Most people understood that it was intended that you're compiling in a Vista env. The question made no reference to runtime behaviour.
Unless someone is running Vista, and compiling for windows XP maybe?
Sheesh!
HTH
cheers,
The Microsoft compiler will define _WIN64 when compiling for 64 bit machines.
http://msdn.microsoft.com/en-us/library/b0084kay%28VS.80%29.aspx
#if defined(_WIN64)
unsigned long long get_tick_count(void) { return GetTickCount64(); }
#else
unsigned long long get_tick_count(void) { return GetTickCount(); }
#endif
If you have to support pre-Vista, I would stick with only using GetTickCount(). Otherwise you have to implement runtime code to check the Windows version and to call GetTickCount() on pre-Vista versions of Windows and GetTickCount64() on Vista and later. Since they return different sized values (ULONGLONG v DWORD) you'll also need to have separate handling of what they return. Using only GetTickCount() (and checking for overflow) will work for both situations, whereas using GetTickCount64() when it's available increases your code complexity and doubles the amount of code you have to write.
Stick with using only GetTickCount() until you can be sure your app no longer has to run on pre-Vista machines.
Maybe it is a good replacement for GetTickCount()
double __stdcall
thetimer (int value)
{
static double freq = 0;
static LARGE_INTEGER first;
static LARGE_INTEGER second;
if (0 == value)
{
if (freq == 0)
{
QueryPerformanceFrequency (&first);
freq = (double) first.QuadPart;
}
QueryPerformanceCounter (&first);
return 0;
}
if (1 == value)
{
QueryPerformanceCounter (&second);
second.QuadPart = second.QuadPart - first.QuadPart;
return (double) second.QuadPart / freq;
}
return 0;
}

Resources