Error c2169 intrinsic function cannot be defined

In visual studio 2005 it was possible to disable an intrinsic function.for example:
  • Remove From My Forums
  • Question

  • In visual studio 2005 it was possible to disable an intrinsic function.
    for example:

        #pragma function(_inp)

    Or all intrinsics could be disabled using the command line option /Oi-
    Or it can be unselected from the GUI under Optimization «Enable Intrinsic Functions».

    These procedures no longer seem to work in Visual Studio 2008 Express Edition.
    The compiler reports (Using _inp for example):

        error C2169: ‘_inp’ : intrinsic function, cannot be defined


    Is this a bug? Is it fixed in the non-free version of Visual C++?

    Thanks for any solution or workarounds (we have a large body
    of software that uses one of the intrinsic names.)

Answers

  • Yes, that pragma is fighting a losing battle.  The missing support for __asm in x64 code makes its future look very bleak.  It can’t be a real problem, you can give your function any name other than _inp().  You are supposed to, identifiers with leading underscores are reserved to the vendor.  The Express edition uses the same version of the compiler as the retail edition.


    Hans Passant.

    • Marked as answer by

      Monday, July 27, 2009 2:52 AM

I’m involved in one of those challenges where you try to produce the smallest possible binary, so I’m building my program without the C or C++ run-time libraries (RTL). I don’t link to the DLL version or the static version. I don’t even #include the header files. I have this working fine.

Some RTL functions, like memset(), can be useful, so I tried adding my own implementation. It works fine in Debug builds (even for those places where the compiler generates an implicit call to memset()). But in Release builds, I get an error saying that I cannot define an intrinsic function. You see, in Release builds, intrinsic functions are enabled, and memset() is an intrinsic.

I would love to use the intrinsic for memset() in my release builds, since it’s probably inlined and smaller and faster than my implementation. But I seem to be a in catch-22. If I don’t define memset(), the linker complains that it’s undefined. If I do define it, the compiler complains that I cannot define an intrinsic function.

Does anyone know the right combination of definition, declaration, #pragma, and compiler and linker flags to get an intrinsic function without pulling in RTL overhead?

Visual Studio 2008, x86, Windows XP+.

To make the problem a little more concrete:

extern "C" void * __cdecl memset(void *, int, size_t);

#ifdef IMPLEMENT_MEMSET
void * __cdecl memset(void *pTarget, int value, size_t cbTarget) {
    char *p = reinterpret_cast<char *>(pTarget);
    while (cbTarget > 0) {
        *p++ = static_cast<char>(value);
        --cbTarget;
    }
    return pTarget;
}
#endif

struct MyStruct {
    int foo[10];
    int bar;
};

int main() {
    MyStruct blah;
    memset(&blah, 0, sizeof(blah));
    return blah.bar;
}

And I build like this:

cl /c /W4 /WX /GL /Ob2 /Oi /Oy /Gs- /GF /Gy intrinsic.cpp
link /SUBSYSTEM:CONSOLE /LTCG /DEBUG /NODEFAULTLIB /ENTRY:main intrinsic.obj

If I compile with my implementation of memset(), I get a compiler error:

error C2169: 'memset' : intrinsic function, cannot be defined

If I compile this without my implementation of memset(), I get a linker error:

error LNK2001: unresolved external symbol _memset

I’m involved in one of those challenges where you try to produce the smallest possible binary, so I’m building my program without the C or C++ run-time libraries (RTL). I don’t link to the DLL version or the static version. I don’t even #include the header files. I have this working fine.

Some RTL functions, like memset(), can be useful, so I tried adding my own implementation. It works fine in Debug builds (even for those places where the compiler generates an implicit call to memset()). But in Release builds, I get an error saying that I cannot define an intrinsic function. You see, in Release builds, intrinsic functions are enabled, and memset() is an intrinsic.

I would love to use the intrinsic for memset() in my release builds, since it’s probably inlined and smaller and faster than my implementation. But I seem to be a in catch-22. If I don’t define memset(), the linker complains that it’s undefined. If I do define it, the compiler complains that I cannot define an intrinsic function.

Does anyone know the right combination of definition, declaration, #pragma, and compiler and linker flags to get an intrinsic function without pulling in RTL overhead?

Visual Studio 2008, x86, Windows XP+.

To make the problem a little more concrete:

extern "C" void * __cdecl memset(void *, int, size_t);

#ifdef IMPLEMENT_MEMSET
void * __cdecl memset(void *pTarget, int value, size_t cbTarget) {
    char *p = reinterpret_cast<char *>(pTarget);
    while (cbTarget > 0) {
        *p++ = static_cast<char>(value);
        --cbTarget;
    }
    return pTarget;
}
#endif

struct MyStruct {
    int foo[10];
    int bar;
};

int main() {
    MyStruct blah;
    memset(&blah, 0, sizeof(blah));
    return blah.bar;
}

And I build like this:

cl /c /W4 /WX /GL /Ob2 /Oi /Oy /Gs- /GF /Gy intrinsic.cpp
link /SUBSYSTEM:CONSOLE /LTCG /DEBUG /NODEFAULTLIB /ENTRY:main intrinsic.obj

If I compile with my implementation of memset(), I get a compiler error:

error C2169: 'memset' : intrinsic function, cannot be defined

If I compile this without my implementation of memset(), I get a linker error:

error LNK2001: unresolved external symbol _memset

Добрый вечер, решил использовать динамический импорт и директиву /nodefaultlib для полной минимизации размера модуля.

Все нужные функции импортирую, НО, по непонятным причинам возникает ошибка линковки:
PModule.obj : error LNK2001: unresolved external symbol _memset

Создал маленький проект, туда запихал небольшой код, отказался от црт (/nodefaultlib + /entry:winmain) и все равно возникала эта ошибка! В итоге оказалось, что комментируя WINAPI функцию GetClassName, ошибка исчезала. Возникает ощущение что компилятор сам добавляет memset в проект при определенных условиях. Поэтому вижу только один путь для решения проблемы: описать функцию memset.

При использовании /nodefaultlib, ни одна lib библиотека к проекту не подключается, поэтому таким образом определить memset нельзя. Пробовал прописать напрямую в проекте:

extern "C"
{
     void * memset (void *Dst, int Val, size_t Size)
     {
          return Mmemset(Dst, Val, Size); // импортируемая мною из ntdll функция
     }
}

компилятор орет:
error C2169: ‘memset’ : intrinsic function, cannot be defined

Если указать директиву #pragma intrinsic (memset), то вдобавок к предыдущей ошибке возникает warning C4164: ‘memset’ : intrinsic function not declared

Отключал использование intrinsic-функций (в настройках проекта и добавлением /Oi-) все равно intrinsic function, cannot be defined! Подскажите пожалуйста как решить проблему.

extern "C" void * __cdecl memset(void * const s, int c, size_t n);
#pragma intrinsic(memset)

Этого должно быть достаточно.

Здравствуйте, byleas, Вы писали:

B>

B>extern "C" void * __cdecl memset(void * const s, int c, size_t n);
B>#pragma intrinsic(memset)


B>Этого должно быть достаточно.

недостаточно(

Этой проблеме уже несколько лет.

http://rsdn.ru/forum/cpp.applied/1665635.1.aspx

Автор: MShura
Дата: 07.02.06


RTT>Если указать директиву #pragma intrinsic (memset), то вдобавок к предыдущей ошибке возникает warning C4164: ‘memset’ : intrinsic function not declared


RTT>Отключал использование intrinsic-функций (в настройках проекта и добавлением /Oi-) все равно intrinsic function, cannot be defined! Подскажите пожалуйста как решить проблему.

Избавиться от всех явных и неявных вызовов memset, заменив эти вызовы на явный вызов своей memset.

Здравствуйте, fkRTTI, Вы писали:

RTT>недостаточно(

Ошибся, как inrinsic она только в x64.

Здравствуйте, fkRTTI, Вы писали:

RTT>недостаточно(

…и линкуй с ntdll.lib. Даже если убрать явные вызовы, и заменить их обнулением через for, компилятор вставит вызов memset.

.

People who are more than casually interested in computers should have at least some idea of what the underlying hardware is like. Otherwise the programs they write will be pretty weird (c) D.Knuth

Я перенес проект Visual C ++ в Visual Studio 2013. Когда я пытаюсь построить проект, компилятор возвращает следующую ошибку:

Error 2 error C2169: '_InterlockedIncrement' : intrinsic function, cannot be defined

Ошибка в combase.h (заголовок из DirectShow) и код:

static inline LONG WINAPI InterlockedIncrement(volatile LONG * plong)
{ return InterlockedIncrement( const_cast<LONG*>( plong ) ); }

InterlockedIncrement определяется в winnt.h как:

#define InterlockedIncrement _InterlockedIncrement

Знаете ли вы какое-либо решение для этой ошибки?

0

Решение

Ваш #define заменяет все вхождения InterlockedIncrement с _InterlockedIncrement, так static inline LONG WINAPI InterlockedIncrement(volatile LONG * plong) становится static inline LONG WINAPI _InterlockedIncrement(volatile LONG * plong),

Это означает, что вы на самом деле пытаетесь определить _InterlockedIncrement функция, которая запрещена, так как она является внутренней.

Я думаю, вам нужно удалить

#define InterlockedIncrement _InterlockedIncrement

и сделать InterlockedIncrement вызов _InterlockedIncrement с соответствующим преобразованием аргумента, если это необходимо.

1

Другие решения

Других решений пока нет …

So, I’ve dutifully not (for once) coded «using namespace std;» and I’ve dutifully (for once) stuck «std::» in front of a standard library routine so as not to have an accidental name clash with one of my own functions.

So, which square root function will run from main() and why?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cmath>

double sqrt( double x )
{
   std::cout << "Go away, I'm gonna run my own function on " << x << " if I want to!  ";
   return -999999;
}

int main()
{
   std::cout << "The square root of 4 is ... " << std::sqrt( 4.0 ) << 'n';
}

(If your compiler complains then you can make the function definition
double sqrt( double x ) throw()
It doesn’t change the outcome.)

Last edited on

Strange. My implementation has std::sqrt(float) and std::sqrt(long double), but not std::sqrt(double). Does anyone know which overloads are required by the standard? I’m wondering if it counts as an implementation bug.

Technically the result is unspecified; see https://timsong-cpp.github.io/cppwp/n4659/headers#4

It is unspecified whether these names […] are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations.

It so happens that the implementation(s) you’ve tried it on have

<cmath>

work as if:

1
2
3
4
#include <math.h>
namespace std {
  using sqrt = ::sqrt;
}

…which of course explicit, proper use of

std::

qualifiers won’t save you from, since you’ve just provided a definition of

::sqrt

that matches the declaration provided in

<math.h>

.

Last edited on

So, simply prepending std:: won’t save me from name clashes — I would explicitly have to put my own functions in their own namespaces? That is almost never done in this forum (although I suspect it would be done at work).

I tried it on quite a few implentations … all with the same result.

The issue arose from a std::sin() function used in a different thread.

Last edited on

I had to follow down several layers of includes to get to the declaration of sqrt(long double). This and the overloads seem to be declared globally and then injected into the std:: namespace, so I assume the complier is just matching the definition provided with the declaration (global via the std:: injection).

I believe the standard say something about «It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std.»

Well for the original code, it uses the local def of sqrt() on VS. With VS, AFAIK the c-library functions are defined in :: if <xxx.h> is used and in :: and std:: if <cxxx> is used (pointing to the same :: function). In this case the local function ‘overrides’ the :: one which is the one used by std:: — hence std::sqrt() in this case calls the local version.

If you don’t want the local version to be used but the std:: (or standard ::) one, then you need to put your function in a namespace. Then :: or std:: will call the standard library version and to use your own, you need to call the one in the namespace.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cmath>

//namespace qqq {
	double sqrt(double x)
	{
		std::cout << "Go away, I'm gonna run my own function on " << x << " if I want to!  ";
		return -999999;
	}
//}

int main()
{
	std::cout << "The square root of 4 is ..." << std::sqrt(4.0) << 'n';
}

Calls the local one:


The square root of 4 is ...Go away, I'm gonna run my own function on 4 if I want to!  -999999

but by using a namespace for the local one, it calls the c-library version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cmath>

namespace qqq {
	double sqrt(double x)
	{
		std::cout << "Go away, I'm gonna run my own function on " << x << " if I want to!  ";
		return -999999;
	}
}

int main()
{
	std::cout << "The square root of 4 is ..." << std::sqrt(4.0) << 'n';
}

The square root of 4 is ...2

I totally agree, @seeplus!

However, putting one’s own functions in their own namespace doesn’t get done in this forum. The advice is just «prepend std:: and all will be well».

I seem to remember this coming up a few times in the past…but what can you do? other than here are some good practices but be careful of the odd little bits of the standard that that may trip you up.

People overloading sqrt/sin also doesn’t normally come up in this forum. What you demonstrated is going to be a problem regardless of «using namespace std» when dealing with most C library functions. I’ll usually just tell beginners to not put it in a header file; don’t care when people use it in individual files.

Perhaps a sentence could be added to https://isocpp.org/wiki/faq/coding-standards#using-namespace-std to say «use your own custom namespaces to prevent function overload ambiguities».

People overloading sqrt/sin also doesn’t normally come up in this forum.
No, the ones that get you are the less commonly used things that you forgot was in the giant namespace.
eg, if you were dealing with your own class that handled currency, and had a member money, and like a good code monkey you put in your getters and setters… oops
https://en.cppreference.com/w/cpp/io/manip/get_money

For me VS2019 spits out two errors with the original code:

line 5, «C2169 ‘sqrt’: intrinsic function, cannot be defined»
line 12, «C2264 ‘sqrt’: error in function definition or declaration; function not called»

Remove/comment out the <cmath> header and the errors still barf up. <iostream> includes other headers?

Enclose the custom sqrt function in a custom namespace and VS2019 has no complaint. Even without <cmath> std::sqrt is called.

Curiouser and curiouser….

visual studio is notorious for that. It frequently seems to be able to find things you did not include anywhere, and when you move the code to another compiler the stuff you left off stops working. Its actually better than it was in vs 2008 / vs.net original era and earlier, but they have not completely eradicated the magic.

The original code compiles just fine using Code::Blocks with MinGW-W64 8.1.0. Calling std::sqrt calls the custom function.

Custom namespace for custom function and the C sqrt is called.

Really curiouser and curiouser.

Furry Guy wrote:
For me VS2019 spits out two errors with the original code:

line 5, «C2169 ‘sqrt’: intrinsic function, cannot be defined»
line 12, «C2264 ‘sqrt’: error in function definition or declaration; function not called»

hmm, my VS2019 just gives a warning (C28251: Inconsistent annotation for function: this instance has an error) on the original code. 🤷‍♂️

Edit: Release gives me the errors…

Last edited on

I normally don’t compile code samples like this in debug mode, only release. Lazy, I guess. I never thought to try debug mode. *shrug*

Interesting VS2019 has «relaxed standards» with debug mode vs. release mode.

Maybe I should start using both modes. This example code shows there can be very different results.

Last edited on

With VS2019, release, warning level 4, x64, I get no errors/warnings!

But intellisense suggests warning C28251 for the sqrt function definition.

C28251: Inconsistent annotation for ‘sqrt’. This instance has no annotations.

I’d forget that debug settings default to not allowing intrinsic functions and release defaults to allows them.

Inconsistent annotation for function

Oh, ICK! More SAL in the CRT with MS.

sqrt(double) definition in corecrt_math.h:
_Check_return_ _CRT_JIT_INTRINSIC double __cdecl sqrt(_In_ double _X);

About an intrinsic function with VS…

If a function is an intrinsic, the code for that function is usually inserted inline, avoiding the overhead of a function call and allowing highly efficient machine instructions to be emitted for that function.

https://docs.microsoft.com/en-us/cpp/intrinsics/compiler-intrinsics?view=msvc-160

Learn something new everyday. :)

Whether it is a standard header or not, it is reasonable to expect that the programmer who #includes a header is expected to be aware of the names (at least the global names) that are (could be) brought in by that header. This does not solve all problems when we switch to a new revision of the standard if it does introduces additional names which are also visible in the global namespace.

Is overriding a function of a library in accordance with C++ standard?

The following code is passed by the VS 2005 and Dev C++.

#include <cstdlib>
#include <iostream>

using namespace std;

size_t strlen(const char* p)
{
return 0;
} // !!! Note this !!! The standard library function strlen is deliberately overriden.

int main(int argc, char *argv[])
{
int n = strlen(«Hello»); // n equals 0

system(«PAUSE»);

return EXIT_SUCCESS;
}

There is even no warning after compiling the code. In front of the fact, I have to make a guess that all the C++ compilers are conformed to the following rules:

1) The compiler first compiles all the source file included in the project into object files;

2) At link time, the compiler first searches the object files for all the unresolved symbols; if it fails to find some symbols, then the compiler will search the libraries which are included in the project to find the symbols.

3) If the object files containes a symbol, then the symbols that have the same name in the libraries will be ignored.

Am I correct?

Any help will be appreciated. Many thanks in advance.

[Edited by — cqulyx on August 25, 2006 1:59:07 AM]

God said: «Let there be light!» and there was light.

If you didn’t include <cstring>, then the compiler doesn’t know anything about strlen().

Edit:
Nevermind, I was barking up the wrong tree. And apparently you DON’T have to include <cstring> for strlen.

Edit2:
I think you don’t run into any compilation errors because you never try to use the function.

skulldrudgery—A tricky bit of toil

on visual studio expression, with the code

#include

size_t strlen( const char* )
{
return 0;
}

I got: error C2169: ‘strlen’ : intrinsic function, cannot be defined

err that first line was #include windows.h

anyways! it’s really not a good idea, because if anyone else uses it, they would assume that they’re calling the library function and not the overloaded one.

It’s not in accordance with good programming or software engineering practices at least. If you’re going to do something like that, have a wrapper class or library.

Quote:Original post by skulldrudgery
If you didn’t include <cstring>, then the compiler doesn’t know anything about strlen().

I’m sure that what you said is incorrect. If you comment the function definition of strlen provided by the user, you can see that the compiler calls the default version of the function.

Quote:Original post by skulldrudgery
Edit:
Nevermind, I was barking up the wrong tree. And apparently you DON’T have to include <cstring> for strlen.

This is unrelated to inclusion.

Quote:Original post by skulldrudgery
Edit2:
I think you don’t run into any compilation errors because you never try to use the function.

Even if I use strlen(«Hello»); in main() body, the compiler still doesn’t give me any complaint.

God said: «Let there be light!» and there was light.

I don’t know what the standard says about this but I’ve certainly used this kind of overriding on several compilers/linkers (GCC, CW, VS at least). Well, it’s really the linker that does the trick though. I did it because some of the standard library stuff was broken on the platforms I was developing for, so I had to write working (non-crashing) versions myself. I’d definitely recommend against changing the functionality though, since all the code you link statically against would then use your new strlen functionality and code not written by you probably wouldn’t work because of it. People reading the code would also be surprised to learn that strlen isn’t the strlen they’re used to (including you 5 years from now).

It’s actually amusing.. Seems like a compiler bug to me.. I have tried compiling the bellow program with visual studio 2005 and got 1 error during first try of compilation.. But when tried compiling the same program a second time it passed with 0 warnings and 0 errors.

I don’t know if there’s anything special with standard libraries. I have always treaten them as ordinary additional libraries. To my current knowledge they should obey the ODR (One Definition Rule). Meaning that a non-static function can defined only once per program.

For my best knowledge it’s uncommon practice to override standard functions. Personally I would probably curse the programmer who would override standard functions and caused a bug on the way. Hunting such bugs can be very time concuming, especially when you expect something to work because it was made by the experts and was tested by huge amount of programmers(people that use standard libraries). Other than that, I advise you to stop working with C functions and move on to CPP, such as std::string class. Even though it’s bit bloated, it has more advantages over C functions.

#include <cstring>size_t  strlen(const char *){  return 0;}void main(){  strlen("123");}  Compiling...1.cppLinking...1.obj : error LNK2005: _strlen already defined in MSVCRTD.lib(MSVCR80D.dll)D:CPP ProjectsgdDebuggd.exe : fatal error LNK1169: one or more multiply defined symbols foundBuild log was saved at "file://d:CPP ProjectsgdDebugBuildLog.htm"gd - 2 error(s), 0 warning(s)========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

HTH,
Shimon

«If you’re stuck, ask for help. If you keep running up against the same wall, take a break and see if you can find a different wall.»

Quote:Original post by Anonymous Poster
anyways! it’s really not a good idea, because if anyone else uses it, they would assume that they’re calling the library function and not the overloaded one.

In some cases it wouldn’t matter as much. Such as if you just wanted to deal with null pointers as though they are empty strings in functions like strcmp(). I’m pretty sure most of the standard string functions throw an error or access violation.

But I still agree that a wrapper would be better.

I’m a bit confused here — surely if you include <cstring> with a properly standards-compliant C++ compiler, the library strlen would be in the std namespace so you would be free to declare another strlen in the global or your own namespace without a conflict?

Or does this not apply if it is included via <windows.h>?

>
Непонятный Warning
, и непонятная секция

  • Подписаться на тему
  • Сообщить другу
  • Скачать/распечатать тему



Сообщ.
#16

,
16.02.06, 19:00

    Цитата rmf @ 16.02.06, 18:41

    Цитата

    Сам себе геморрой и ищешь…. 6к жалко. Офигеть…

    Мда… наверное ты прав, но на си я перехожу из-за маленького размера, хочется пользоватся этой возможностью по полной!

    Переходи на ассемблер — там всего будет по-полной…

    Цитата

    но блин, из списка вызываемых библиотек, и ф-ций исчез только strstr!!! хотя заменил все ф-ции! в чем может быть дело? :(

    Значит, кто-то продолжает их юзать. /NODEFAULLIB применял?


    rmf



    Сообщ.
    #17

    ,
    16.02.06, 19:15

      Junior

      *

      Рейтинг (т): 1

      и на асме пробовал, далье программ типа вызова нескольких апи не решился пойти, решил на си остановится!

      угу, получаю
      myprj.obj : error LNK2001: unresolved external symbol _memcpy
      myprj.obj : error LNK2001: unresolved external symbol _memset

      Цитата

      Значит, кто-то продолжает их юзать.

      Кто? в коде нету их вызова!

      Сообщение отредактировано: rmf — 16.02.06, 19:19


      Hryak



      Сообщ.
      #18

      ,
      16.02.06, 19:38

        Цитата rmf @ 16.02.06, 19:15

        Цитата

        Значит, кто-то продолжает их юзать.

        Кто? в коде нету их вызова!

        Компилятор. Вполне может memset вставить на безобидную конструкцию вроде int a[1000] = { 0 };
        Выход — напиши свою функцию memset и memcpy, чтобы он не волновался


        rmf



        Сообщ.
        #19

        ,
        16.02.06, 19:56

          Junior

          *

          Рейтинг (т): 1

          Хм.. вот это я сглупил, точно, можно было создать ф-ции с этми именами,
          но вот ещё что случилось :)
          теперь показывает ошибку

          .myprj.cpp(129) : error C3861: ‘memset’: identifier not found
          на строку FillMemory(recvbuffer,1024,0);
          (ну и на другие тоже, где используются эти ф-ции)

          ну и как это объяснить? memset использует FillMemory, или наоборот?

          в Delphi IDE если нажать на Ctrl и мышкой на имя ф-ции, то показывается где она объявленна и её код, в VS такое можно?

          Добавлено 16.02.06, 20:00
          ой, и ещё ошибки:

          myfunc.cpp(13) : error C2169: ‘memcpy’ : intrinsic function, cannot be defined
          myfunc.cpp(18) : error C2169: ‘memset’ : intrinsic function, cannot be defined

          Сообщение отредактировано: rmf — 16.02.06, 20:00


          Hryak



          Сообщ.
          #20

          ,
          16.02.06, 20:09

            Цитата rmf @ 16.02.06, 19:56

            ну и как это объяснить? memset использует FillMemory, или наоборот?

            FillMemory — это макрос, и раскрывающийся в memset (совсем дырявая голова стала :( ). Вообщем, напиши целиком свои функции, благо это несложно.

            Цитата

            в Delphi IDE если нажать на Ctrl и мышкой на имя ф-ции, то показывается где она объявленна и её код, в VS такое можно?

            Правая кнопка — «Go To Definition»

            Цитата

            myfunc.cpp(13) : error C2169: ‘memcpy’ : intrinsic function, cannot be defined
            myfunc.cpp(18) : error C2169: ‘memset’ : intrinsic function, cannot be defined

            Попробуй написать:

            ExpandedWrap disabled

              #pragma function(memset, memcpy)

            Сообщение отредактировано: Hryak — 16.02.06, 20:09


            rmf



            Сообщ.
            #21

            ,
            16.02.06, 20:21

              Junior

              *

              Рейтинг (т): 1

              #pragma function(memset, memcpy), угу, 2 ошибки ичесли, а что она делает?

              FillMemory — это макрос, и раскрывающийся в memset
              т.е. FillMemory это не замена memset, а всего лишь вызов memset, и надо написать свой аналог memset? правильно понял?


              Hryak



              Сообщ.
              #22

              ,
              16.02.06, 21:19

                Цитата rmf @ 16.02.06, 20:21

                #pragma function(memset, memcpy), угу, 2 ошибки ичесли, а что она делает?

                Это указание компилятору не пытаться использовать встраиваемые версии данных фукнций.

                Цитата

                т.е. FillMemory это не замена memset, а всего лишь вызов memset, и надо написать свой аналог memset? правильно понял?

                Да.


                Adil



                Сообщ.
                #23

                ,
                17.02.06, 14:04

                  Используй RtlFillMemory и иже с ним из kernel32.lib. Тока на одноименные макросы не нарвись :)

                  Добавлено 17.02.06, 14:22
                  Нечто вроде

                  ExpandedWrap disabled

                    #ifdef RtlFillMemory

                    #undef RtlFillMemory

                    #endif

                    extern «C» NTSYSAPI VOID NTAPI RtlFillMemory ( VOID UNALIGNED *Destination,

                        SIZE_T Length,

                        IN BYTE  Fill

                        );

                        char ss[10];

                        RtlFillMemory(ss,10,0×22);

                  Сообщение отредактировано: Adil — 17.02.06, 14:37


                  rmf

                    


                  Сообщ.
                  #24

                  ,
                  18.02.06, 12:01

                    Junior

                    *

                    Рейтинг (т): 1

                    Ну а как сделать? пишу что то типа

                    ExpandedWrap disabled

                      void *memset( void *dest, int i, size_t count )

                      {

                          void *dst;

                          RtlFillMemory(dst,count,i);

                          return dst;

                      }

                    а он пишет warning C4717: ‘memset’ : recursive on all control paths, function will cause runtime stack overflow

                    и что это значит? опять эта ф-ция использует memset? Как полностью замениить memset (ну и memcpy)?


                    Hryak



                    Сообщ.
                    #25

                    ,
                    18.02.06, 15:47

                      Цитата rmf @ 18.02.06, 12:01

                      Как полностью замениить memset (ну и memcpy)?

                      Ну напиши сам-то.

                      ExpandedWrap disabled

                        /***

                        *char *memset(dst, val, count) — sets «count» bytes at «dst» to «val»

                        *

                        *Purpose:

                        *       Sets the first «count» bytes of the memory starting

                        *       at «dst» to the character value «val».

                        *

                        *Entry:

                        *       void *dst — pointer to memory to fill with val

                        *       int val   — value to put in dst bytes

                        *       size_t count — number of bytes of dst to fill

                        *

                        *Exit:

                        *       returns dst, with filled bytes

                        *

                        *Exceptions:

                        *

                        *******************************************************************************/

                        void * __cdecl memset (

                                void *dst,

                                int val,

                                size_t count

                                )

                        {

                                void *start = dst;

                        #if defined (_M_IA64) || defined (_M_AMD64)

                                {

                                __declspec(dllimport)

                                void RtlFillMemory( void *, size_t count, char );

                                RtlFillMemory( dst, count, (char)val );

                                }

                        #else  /* defined (_M_IA64) || defined (_M_AMD64) */

                                while (count—) {

                                        *(char *)dst = (char)val;

                                        dst = (char *)dst + 1;

                                }

                        #endif  /* defined (_M_IA64) || defined (_M_AMD64) */

                                return(start);

                        }

                        /***

                        *memcpy — Copy source buffer to destination buffer

                        *

                        *Purpose:

                        *       memcpy() copies a source memory buffer to a destination memory buffer.

                        *       This routine does NOT recognize overlapping buffers, and thus can lead

                        *       to propogation.

                        *

                        *       For cases where propogation must be avoided, memmove() must be used.

                        *

                        *Entry:

                        *       void *dst = pointer to destination buffer

                        *       const void *src = pointer to source buffer

                        *       size_t count = number of bytes to copy

                        *

                        *Exit:

                        *       Returns a pointer to the destination buffer

                        *

                        *Exceptions:

                        *******************************************************************************/

                        void * __cdecl memcpy (

                                void * dst,

                                const void * src,

                                size_t count

                                )

                        {

                                void * ret = dst;

                        #if defined (_M_IA64)

                                {

                                __declspec(dllimport)

                                void RtlCopyMemory( void *, const void *, size_t count );

                                RtlCopyMemory( dst, src, count );

                                }

                        #else  /* defined (_M_IA64) */

                                /*

                                 * copy from lower addresses to higher addresses

                                 */

                                while (count—) {

                                        *(char *)dst = *(char *)src;

                                        dst = (char *)dst + 1;

                                        src = (char *)src + 1;

                                }

                        #endif  /* defined (_M_IA64) */

                                return(ret);

                        }

                      Copyright © Microsoft Corporation. All rights reserved.


                      rmf



                      Сообщ.
                      #26

                      ,
                      18.02.06, 17:04

                        Junior

                        *

                        Рейтинг (т): 1

                        Ну дык еслибы знал бы, написал бы!
                        (яж говорю, я с Delphi, и особо не понимаю, смысл этого- выделение, осовобождение памяти, и т.д. Как там легко сделать str1:=str1+str2+’hello’, а здесь… ф-ции вызывать)

                        Ты где этот код взял(дай пожалуйста и на strrchr и strstr, а то я свои версии сделал, но не уверен что они безглючные, и лучше MS’овских)? На Go To Defenition другое совсем!

                        Добавлено 18.02.06, 17:05
                        З.Ы. пасибо большое, столько времени потратил на меня!

                        Сообщение отредактировано: rmf — 18.02.06, 18:14


                        rmf



                        Сообщ.
                        #27

                        ,
                        18.02.06, 19:03

                          Junior

                          *

                          Рейтинг (т): 1

                          Всё, спасибо, нашел сам!
                          C:Program FilesVisual Studio 8VCcrtsrc

                          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                          0 пользователей:

                          • Предыдущая тема
                          • Visual C++ / MFC / WTL
                          • Следующая тема

                          [ Script execution time: 0,0620 ]   [ 16 queries used ]   [ Generated: 9.02.23, 12:12 GMT ]  

                          Понравилась статья? Поделить с друзьями:
                        • Error c2144 syntax error void should be preceded by
                        • Error c2144 syntax error int should be preceded by
                        • Error c2143 синтаксическая ошибка отсутствие перед строка
                        • Error c2143 синтаксическая ошибка отсутствие перед using namespace
                        • Error c2143 синтаксическая ошибка отсутствие перед class head